/*
 * @(#)FormSubmission.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.form.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import com.dcivision.form.bean.FormElementType;
import com.dcivision.form.bean.FormRecord;
import com.dcivision.form.bean.FormSubmission;
import com.dcivision.form.web.ListFormRecordForm;
import com.dcivision.form.web.ListFormSubmissionForm;
import com.dcivision.form.web.MaintFormSubmissionForm;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.DataSourceFactory;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.UserInfoFactory;
import com.dcivision.framework.Utility;
import com.dcivision.framework.bean.AbstractBaseObject;
import com.dcivision.framework.dao.AbstractDAObject;
import com.dcivision.framework.dao.AbstractQuery;
import com.dcivision.framework.dao.QueryUtil;
import com.dcivision.framework.dao.SubQuery;
import com.dcivision.framework.web.AbstractActionForm;
import com.dcivision.framework.web.AbstractSearchForm;
import com.dcivision.workflow.bean.WorkflowProgress;
import com.dcivision.workflow.bean.WorkflowStep;
import com.dcivision.workflow.core.SystemWorkflowConstant;
import com.dcivision.workflow.dao.WorkflowRecordDAObject;
import com.dcivision.workflow.dao.WorkflowStepDAObject;

/**
  FormSubmissionDAObject.java

  This class is the data access bean for table "FORM_SUBMISSION".

  @author      Scott Tong
  @company     DCIVision Limited
  @creation date   08/01/2004
  @version     $Revision: 1.93.2.5 $
*/

public class FormSubmissionDAObject extends AbstractDAObject {

  public static final String REVISION = "$Revision: 1.93.2.5 $";

  public static final String TABLE_NAME = "FORM_SUBMISSION";

  public FormSubmissionDAObject(SessionContainer sessionContainer, Connection dbConn) {
    super(sessionContainer, dbConn);
  }

  protected void initDBSetting() {
    this.baseTableName = TABLE_NAME;
    this.vecDBColumn.add("ID");
    this.vecDBColumn.add("TRACK_ID");
    this.vecDBColumn.add("FORM_RECORD_ID");
    this.vecDBColumn.add("WORKFLOW_RECORD_ID");
    this.vecDBColumn.add("IP");
    this.vecDBColumn.add("GUEST_NAME");
    this.vecDBColumn.add("EMAIL");
    this.vecDBColumn.add("CONTACT_INFO");
    this.vecDBColumn.add("DMS_PARENT_ID");
    this.vecDBColumn.add("STATUS");
    this.vecDBColumn.add("RECORD_STATUS");
    this.vecDBColumn.add("UPDATE_COUNT");
    this.vecDBColumn.add("CREATOR_ID");
    this.vecDBColumn.add("CREATE_DATE");
    this.vecDBColumn.add("UPDATER_ID");
    this.vecDBColumn.add("UPDATE_DATE");
  }

  protected synchronized AbstractBaseObject getByID(Integer id) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.TRACK_ID, A.FORM_RECORD_ID, A.WORKFLOW_RECORD_ID, A.IP, A.GUEST_NAME, A.EMAIL, A.CONTACT_INFO, A.DMS_PARENT_ID, A.STATUS, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   FORM_SUBMISSION A ");
        sqlStat.append("WHERE  A.ID = ? AND A.RECORD_STATUS = ? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, id);
        this.setPrepareStatement(preStat, 2, GlobalConstant.RECORD_STATUS_ACTIVE);
        rs = preStat.executeQuery();
        if (rs.next()) {
          FormSubmission tmpFormSubmission = new FormSubmission();
          tmpFormSubmission.setID(getResultSetInteger(rs, "ID"));
          tmpFormSubmission.setTrackID(getResultSetInteger(rs, "TRACK_ID"));
          tmpFormSubmission.setFormRecordID(getResultSetInteger(rs, "FORM_RECORD_ID"));
          tmpFormSubmission.setWorkflowRecordID(getResultSetInteger(rs, "WORKFLOW_RECORD_ID"));
          tmpFormSubmission.setIp(getResultSetString(rs, "IP"));
          tmpFormSubmission.setGuestName(getResultSetString(rs, "GUEST_NAME"));
          tmpFormSubmission.setEmail(getResultSetString(rs, "EMAIL"));
          tmpFormSubmission.setContactInfo(getResultSetString(rs, "CONTACT_INFO"));
          tmpFormSubmission.setDmsParentID(getResultSetInteger(rs, "DMS_PARENT_ID"));
          tmpFormSubmission.setStatus(getResultSetString(rs, "STATUS"));
          tmpFormSubmission.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormSubmission.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormSubmission.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormSubmission.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpFormSubmission.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpFormSubmission.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpFormSubmission.setCreatorName(UserInfoFactory.getUserFullName(tmpFormSubmission.getCreatorID()));
          tmpFormSubmission.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormSubmission.getUpdaterID()));
          return(tmpFormSubmission);
        } else {
          throw new ApplicationException(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized List getList(AbstractSearchForm searchForm) throws ApplicationException {
    PreparedStatement preStat = null;
    PreparedStatement preStatCnt = null;
    ResultSet rs = null;
    ResultSet rsCnt = null;
    StringBuffer sqlStat = new StringBuffer();
    StringBuffer sqlStatCnt = new StringBuffer();
    List result = new ArrayList();
    int totalNumOfRecord = 0;
    int rowLoopCnt = 0;
    int startOffset = TextUtility.parseInteger(searchForm.getCurStartRowNo());
    int pageSize = TextUtility.parseInteger(searchForm.getPageOffset());

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.TRACK_ID, A.FORM_RECORD_ID, A.WORKFLOW_RECORD_ID, A.IP, A.GUEST_NAME, A.EMAIL, A.CONTACT_INFO, A.DMS_PARENT_ID, A.STATUS, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   FORM_SUBMISSION A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? ");

        // Form the WHERE clause for filtering.
        if (searchForm.isSearchable()) {
          String searchField = getSearchColumn(searchForm.getBasicSearchField());
          sqlStat.append("AND  " + searchField + " " + searchForm.getBasicSearchType() + " ? ");
        }

        //format the sql for any 'LIKE' statement contained
        sqlStat = this.getFormattedSQL(sqlStat.toString());

        // Form the ORDER clause for sorting.
        if (searchForm.isSortable()) {
          String sortAttribute = searchForm.getSortAttribute();
          if (sortAttribute.indexOf(".") < 0) {
            sortAttribute = "A." + sortAttribute;
          }
          sqlStat.append("ORDER BY " + sortAttribute + " " + searchForm.getSortOrder());
        }

        // Get total number of record return.
        sqlStatCnt = this.getSelectCountSQL(sqlStat);
        preStatCnt = dbConn.prepareStatement(sqlStatCnt.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStatCnt, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          this.setPrepareStatement(preStatCnt, 2, searchKeyword);
        }
        rsCnt = preStatCnt.executeQuery();
        if (rsCnt.next()) {
          totalNumOfRecord = rsCnt.getInt(1);
        }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }

        // Retrieve the result in row basis.
        sqlStat = this.getSelectListSQL(sqlStat, startOffset, pageSize);
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          this.setPrepareStatement(preStat, 2, searchKeyword);
        }
        rs = preStat.executeQuery();

        this.positionCursor(rs, startOffset, pageSize);

        while (rs.next() && rowLoopCnt<pageSize) {
          FormSubmission tmpFormSubmission = new FormSubmission();
          tmpFormSubmission.setID(getResultSetInteger(rs, "ID"));
          tmpFormSubmission.setTrackID(getResultSetInteger(rs, "TRACK_ID"));
          tmpFormSubmission.setFormRecordID(getResultSetInteger(rs, "FORM_RECORD_ID"));
          tmpFormSubmission.setWorkflowRecordID(getResultSetInteger(rs, "WORKFLOW_RECORD_ID"));
          tmpFormSubmission.setIp(getResultSetString(rs, "IP"));
          tmpFormSubmission.setGuestName(getResultSetString(rs, "GUEST_NAME"));
          tmpFormSubmission.setEmail(getResultSetString(rs, "EMAIL"));
          tmpFormSubmission.setContactInfo(getResultSetString(rs, "CONTACT_INFO"));
          tmpFormSubmission.setDmsParentID(getResultSetInteger(rs, "DMS_PARENT_ID"));
          tmpFormSubmission.setStatus(getResultSetString(rs, "STATUS"));
          tmpFormSubmission.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormSubmission.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormSubmission.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormSubmission.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpFormSubmission.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpFormSubmission.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpFormSubmission.setCreatorName(UserInfoFactory.getUserFullName(tmpFormSubmission.getCreatorID()));
          tmpFormSubmission.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormSubmission.getUpdaterID()));
          tmpFormSubmission.setRecordCount(totalNumOfRecord);
          tmpFormSubmission.setRowNum(startOffset++);
          ++rowLoopCnt;
          result.add(tmpFormSubmission);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }
      }
    }
  }

  protected synchronized List getList() throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.TRACK_ID, A.FORM_RECORD_ID, A.WORKFLOW_RECORD_ID, A.IP, A.GUEST_NAME, A.EMAIL, A.CONTACT_INFO, A.DMS_PARENT_ID, A.STATUS, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   FORM_SUBMISSION A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        rs = preStat.executeQuery();
        while (rs.next()) {
          FormSubmission tmpFormSubmission = new FormSubmission();
          tmpFormSubmission.setID(getResultSetInteger(rs, "ID"));
          tmpFormSubmission.setTrackID(getResultSetInteger(rs, "TRACK_ID"));
          tmpFormSubmission.setFormRecordID(getResultSetInteger(rs, "FORM_RECORD_ID"));
          tmpFormSubmission.setWorkflowRecordID(getResultSetInteger(rs, "WORKFLOW_RECORD_ID"));
          tmpFormSubmission.setIp(getResultSetString(rs, "IP"));
          tmpFormSubmission.setGuestName(getResultSetString(rs, "GUEST_NAME"));
          tmpFormSubmission.setEmail(getResultSetString(rs, "EMAIL"));
          tmpFormSubmission.setContactInfo(getResultSetString(rs, "CONTACT_INFO"));
          tmpFormSubmission.setDmsParentID(getResultSetInteger(rs, "DMS_PARENT_ID"));
          tmpFormSubmission.setStatus(getResultSetString(rs, "STATUS"));
          tmpFormSubmission.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormSubmission.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormSubmission.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormSubmission.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpFormSubmission.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpFormSubmission.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpFormSubmission.setCreatorName(UserInfoFactory.getUserFullName(tmpFormSubmission.getCreatorID()));
          tmpFormSubmission.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormSubmission.getUpdaterID()));
          result.add(tmpFormSubmission);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected void validateInsert(AbstractBaseObject obj) throws ApplicationException {
  }

  protected void validateUpdate(AbstractBaseObject obj) throws ApplicationException {
  }

  protected void validateDelete(AbstractBaseObject obj) throws ApplicationException {
  }

  protected synchronized AbstractBaseObject insert(AbstractBaseObject obj) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    FormSubmission tmpFormSubmission = (FormSubmission)((FormSubmission)obj).clone();

    synchronized(dbConn) {
      try {
        Integer nextID = getNextPrimaryID();       
        Timestamp currTime = Utility.getCurrentTimestamp();
        sqlStat.append("INSERT ");
        sqlStat.append("INTO   FORM_SUBMISSION(ID, TRACK_ID, FORM_RECORD_ID, WORKFLOW_RECORD_ID, IP, GUEST_NAME, EMAIL, CONTACT_INFO, DMS_PARENT_ID, STATUS, RECORD_STATUS, UPDATE_COUNT, CREATOR_ID, CREATE_DATE, UPDATER_ID, UPDATE_DATE) ");
        sqlStat.append("VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setPrepareStatement(preStat, 1, nextID);
        setPrepareStatement(preStat, 2, tmpFormSubmission.getTrackID());
        setPrepareStatement(preStat, 3, tmpFormSubmission.getFormRecordID());
        setPrepareStatement(preStat, 4, tmpFormSubmission.getWorkflowRecordID());
        setPrepareStatement(preStat, 5, tmpFormSubmission.getIp());
        setPrepareStatement(preStat, 6, tmpFormSubmission.getGuestName());
        setPrepareStatement(preStat, 7, tmpFormSubmission.getEmail());
        setPrepareStatement(preStat, 8, tmpFormSubmission.getContactInfo());
        setPrepareStatement(preStat, 9, tmpFormSubmission.getDmsParentID());
        setPrepareStatement(preStat, 10, tmpFormSubmission.getStatus());
        setPrepareStatement(preStat, 11, GlobalConstant.RECORD_STATUS_ACTIVE);
        setPrepareStatement(preStat, 12, new Integer(0));
        setPrepareStatement(preStat, 13, sessionContainer.getUserRecordID());
        setPrepareStatement(preStat, 14, currTime);
        setPrepareStatement(preStat, 15, sessionContainer.getUserRecordID());
        setPrepareStatement(preStat, 16, currTime);
        preStat.executeUpdate();
        tmpFormSubmission.setID(nextID);
        tmpFormSubmission.setCreatorID(sessionContainer.getUserRecordID());
        tmpFormSubmission.setCreateDate(currTime);
        tmpFormSubmission.setUpdaterID(sessionContainer.getUserRecordID());
        tmpFormSubmission.setUpdateDate(currTime);
        tmpFormSubmission.setUpdateCount(new Integer(0));
        tmpFormSubmission.setCreatorName(UserInfoFactory.getUserFullName(tmpFormSubmission.getCreatorID()));
        tmpFormSubmission.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormSubmission.getUpdaterID()));
        return(tmpFormSubmission);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_INSERT_ERROR, e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized AbstractBaseObject update(AbstractBaseObject obj) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    FormSubmission tmpFormSubmission = (FormSubmission)((FormSubmission)obj).clone();

    synchronized(dbConn) {
      try {
        int updateCnt = 0;
        Timestamp currTime = Utility.getCurrentTimestamp();
        sqlStat.append("UPDATE FORM_SUBMISSION ");
        sqlStat.append("SET  TRACK_ID=?, FORM_RECORD_ID=?, WORKFLOW_RECORD_ID=?, IP=?, GUEST_NAME=?, EMAIL=?, CONTACT_INFO=?, DMS_PARENT_ID=?, STATUS=?, UPDATE_COUNT=?, UPDATER_ID=?, UPDATE_DATE=? ");
        sqlStat.append("WHERE  ID=? AND UPDATE_COUNT=? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setPrepareStatement(preStat, 1, tmpFormSubmission.getTrackID());
        setPrepareStatement(preStat, 2, tmpFormSubmission.getFormRecordID());
        setPrepareStatement(preStat, 3, tmpFormSubmission.getWorkflowRecordID());
        setPrepareStatement(preStat, 4, tmpFormSubmission.getIp());
        setPrepareStatement(preStat, 5, tmpFormSubmission.getGuestName());
        setPrepareStatement(preStat, 6, tmpFormSubmission.getEmail());
        setPrepareStatement(preStat, 7, tmpFormSubmission.getContactInfo());
        setPrepareStatement(preStat, 8, tmpFormSubmission.getDmsParentID());
        setPrepareStatement(preStat, 9, tmpFormSubmission.getStatus());
        setPrepareStatement(preStat, 10, new Integer(tmpFormSubmission.getUpdateCount().intValue() + 1));
        if (!Utility.isEmpty(tmpFormSubmission.getUpdaterID())){
          setPrepareStatement(preStat, 11, tmpFormSubmission.getUpdaterID());
        }else{
          setPrepareStatement(preStat, 11, sessionContainer.getUserRecordID());
        }
        setPrepareStatement(preStat, 12, currTime);
        setPrepareStatement(preStat, 13, tmpFormSubmission.getID());
        setPrepareStatement(preStat, 14, tmpFormSubmission.getUpdateCount());
        updateCnt = preStat.executeUpdate();
        if (updateCnt == 0) {
          throw new ApplicationException(ErrorConstant.DB_CONCURRENT_ERROR);
        } else {
          tmpFormSubmission.setUpdaterID(sessionContainer.getUserRecordID());
          tmpFormSubmission.setUpdateDate(currTime);
          tmpFormSubmission.setUpdateCount(new Integer(tmpFormSubmission.getUpdateCount().intValue() + 1));
          tmpFormSubmission.setCreatorName(UserInfoFactory.getUserFullName(tmpFormSubmission.getCreatorID()));
          tmpFormSubmission.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormSubmission.getUpdaterID()));
          return(tmpFormSubmission);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_UPDATE_ERROR, e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized AbstractBaseObject delete(AbstractBaseObject obj) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    FormSubmission tmpFormSubmission = (FormSubmission)((FormSubmission)obj).clone();

    synchronized(dbConn) {
      try {
        int updateCnt = 0;
        sqlStat.append("DELETE ");
        sqlStat.append("FROM   FORM_SUBMISSION ");
        sqlStat.append("WHERE  ID=? AND UPDATE_COUNT=? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setPrepareStatement(preStat, 1, tmpFormSubmission.getID());
        setPrepareStatement(preStat, 2, tmpFormSubmission.getUpdateCount());
        updateCnt = preStat.executeUpdate();
        if (updateCnt == 0) {
          throw new ApplicationException(ErrorConstant.DB_CONCURRENT_ERROR);
        } else {
          return(tmpFormSubmission);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_DELETE_ERROR, e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized void auditTrail(String opMode, AbstractBaseObject obj) throws ApplicationException {
    Vector oldValues = new Vector();
    Vector newValues = new Vector();
    FormSubmission tmpFormSubmission = (FormSubmission)this.oldValue;

    if (tmpFormSubmission != null) {
      oldValues.add(toAuditTrailValue(tmpFormSubmission.getID()));
      oldValues.add(toAuditTrailValue(tmpFormSubmission.getTrackID()));
      oldValues.add(toAuditTrailValue(tmpFormSubmission.getFormRecordID()));
      oldValues.add(toAuditTrailValue(tmpFormSubmission.getWorkflowRecordID()));
      oldValues.add(toAuditTrailValue(tmpFormSubmission.getIp()));
      oldValues.add(toAuditTrailValue(tmpFormSubmission.getGuestName()));
      oldValues.add(toAuditTrailValue(tmpFormSubmission.getEmail()));
      oldValues.add(toAuditTrailValue(tmpFormSubmission.getContactInfo()));
      oldValues.add(toAuditTrailValue(tmpFormSubmission.getStatus()));
      oldValues.add(toAuditTrailValue(tmpFormSubmission.getRecordStatus()));
      oldValues.add(toAuditTrailValue(tmpFormSubmission.getUpdateCount()));
      oldValues.add(toAuditTrailValue(tmpFormSubmission.getCreatorID()));
      oldValues.add(toAuditTrailValue(tmpFormSubmission.getCreateDate()));
      oldValues.add(toAuditTrailValue(tmpFormSubmission.getUpdaterID()));
      oldValues.add(toAuditTrailValue(tmpFormSubmission.getUpdateDate()));
    }

    tmpFormSubmission = (FormSubmission)obj;
    if (tmpFormSubmission != null) {
      newValues.add(toAuditTrailValue(tmpFormSubmission.getID()));
      newValues.add(toAuditTrailValue(tmpFormSubmission.getTrackID()));
      newValues.add(toAuditTrailValue(tmpFormSubmission.getFormRecordID()));
      newValues.add(toAuditTrailValue(tmpFormSubmission.getWorkflowRecordID()));
      newValues.add(toAuditTrailValue(tmpFormSubmission.getIp()));
      newValues.add(toAuditTrailValue(tmpFormSubmission.getGuestName()));
      newValues.add(toAuditTrailValue(tmpFormSubmission.getEmail()));
      newValues.add(toAuditTrailValue(tmpFormSubmission.getContactInfo()));
      newValues.add(toAuditTrailValue(tmpFormSubmission.getStatus()));
      newValues.add(toAuditTrailValue(tmpFormSubmission.getRecordStatus()));
      newValues.add(toAuditTrailValue(tmpFormSubmission.getUpdateCount()));
      newValues.add(toAuditTrailValue(tmpFormSubmission.getCreatorID()));
      newValues.add(toAuditTrailValue(tmpFormSubmission.getCreateDate()));
      newValues.add(toAuditTrailValue(tmpFormSubmission.getUpdaterID()));
      newValues.add(toAuditTrailValue(tmpFormSubmission.getUpdateDate()));
    }

    auditTrailBase(opMode, oldValues, newValues);
  }

  /***********************************************************************
   * DON'T Modify the codes above unless you know what you are doing!!!  *
   * Put your own functions beblow.                                      *
   * For FINDER methods, the function name should be in the notation:    *
   *   public Object getObjectBy<Criteria>()                             *
   *   - e.g. public Object getObjectByCode()                            *
   *   public List getListBy<Criteria>()                                 *
   *   - e.g. public List getListByUserID()                              *
   * For OPERATION methods, the function name should be in the notation: *
   *   public void <Operation>ObjectBy<Criteria>()                       *
   *   - e.g. public void deleteObjectByCode()                           *
   *   public void <Operation>ListBy<Criteria>()                         *
   *   - e.g. public void deleteListByUserID()                           *
   ***********************************************************************/

  /**
   * Get pernsonal submitted form list
   * @param searchForm
   * @return
   * @throws ApplicationException
   */
  public synchronized List getPernsonalSubmittedFormList(AbstractSearchForm searchForm)
      throws ApplicationException {
    return this.getSubmittedFormList(searchForm,true);
  }

  /**
   * Get Save Draft List
   * @param searchForm
   * @return
   * @throws ApplicationException
   */
  public synchronized List getFormSaveDraftListBySearchSection(
      AbstractSearchForm searchForm)
      throws ApplicationException {
    String formRecordID = ((ListFormSubmissionForm)searchForm).getFormRecordID();
    PreparedStatement preStat = null;
    PreparedStatement preStat2 = null;
    PreparedStatement preStatCnt = null;
    ResultSet rs = null;
    ResultSet rs2 = null;
    ResultSet rsCnt = null;
    StringBuffer sqlStat = new StringBuffer();
    StringBuffer sqlStatCnt = new StringBuffer();
    List result = new ArrayList();
    int totalNumOfRecord = 0;
    int rowLoopCnt = 0;
    int startOffset = TextUtility.parseInteger(searchForm.getCurStartRowNo());
    int pageSize = TextUtility.parseInteger(searchForm.getPageOffset());

    ListFormSubmissionForm listFormSubmissionForm = (ListFormSubmissionForm)searchForm;
    String fromDate = listFormSubmissionForm.getFromDate();
    String toDate = TextUtility.dbDateAdder(listFormSubmissionForm.getToDate(), 1);
    String attachedString = "";
    String basicSearchKeyword = listFormSubmissionForm.getBasicSearchKeyword();
    String searchSubmitter = listFormSubmissionForm.getSearchSubmitter();
    StringBuffer sqlStat2 = new StringBuffer();
    String workflowRecordID = listFormSubmissionForm.getWorkflowRecordID();

    if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_ORACLE) {
        if (!Utility.isEmpty(fromDate) && Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE >= TO_DATE('" + fromDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      } else if (Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE <= TO_DATE('" + toDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      } else if (!Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE BETWEEN TO_DATE('" + fromDate + "', 'YYYY-MM-DD HH24:MI:SS') AND TO_DATE('"+  toDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      }
    } else {
        if (!Utility.isEmpty(fromDate) && Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE >= '" + fromDate + "' ";
      } else if (Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE <= '" + toDate + "' ";
      } else if (!Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE BETWEEN '" + fromDate + "' AND '"+  toDate + "' ";
      }
    }

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.FORM_CODE, A.FORM_VERSION, A.TITLE,C.ID, C.TRACK_ID, C.FORM_RECORD_ID, C.WORKFLOW_RECORD_ID, C.IP,C.GUEST_NAME,C.EMAIL,C.CONTACT_INFO, C.DMS_PARENT_ID, C.STATUS,C.RECORD_STATUS,C.UPDATE_COUNT, C.CREATOR_ID, C.CREATE_DATE, C.UPDATER_ID,C.UPDATE_DATE, WR.END_DATE WORKFLOW_END_DATE ");
        sqlStat.append("FROM FORM_RECORD A INNER JOIN FORM_SUBMISSION C ON A.ID = C.FORM_RECORD_ID ");
        sqlStat.append("LEFT JOIN WORKFLOW_RECORD WR ON WR.ID = C.WORKFLOW_RECORD_ID ");
        sqlStat.append("WHERE  A.STATUS = ? AND C.RECORD_STATUS = ? AND C.FORM_RECORD_ID = ? ");
        sqlStat.append("AND C.CREATOR_ID = '"+ sessionContainer.getUserRecordID() +"' ");
        sqlStat.append("AND C.STATUS = '" + FormSubmission.FORM_SUBMISSION_STATU_SAVED + "' ");
        if (!Utility.isEmpty(workflowRecordID) && !"null".equals(workflowRecordID)){
          sqlStat.append("AND C.WORKFLOW_RECORD_ID = " + workflowRecordID + " ");
        } else {
          sqlStat.append("AND C.WORKFLOW_RECORD_ID IS NULL ");
        }
       
        if(!Utility.isEmpty(basicSearchKeyword)){
          // For Text Box
          // Check with "FORM_DATA.DATA_STRING" except "SELECTION_BOX" "RADIO_BUTTON" and "CHECK_BOX";
          
            sqlStat2.append("SELECT DISTINCT E.SUBMISSION_ID FROM FORM_DATA_ELEMENT E, FORM_DATA D, FORM_ELEMENT FE ");
          sqlStat2.append("WHERE D.DATA_ELEMENT_ID = E.ID ");
          sqlStat2.append(" AND E.ELEMENT_ID = FE.ID \n");
          sqlStat2.append(" AND FE.ELEMENT_TYPE <> ? \n");
          sqlStat2.append(" AND FE.ELEMENT_TYPE <> ? \n");
          sqlStat2.append(" AND FE.ELEMENT_TYPE <> ? \n");
          String searchField = searchForm.getBasicSearchField();
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          sqlStat2.append("AND D.DATA_STRING " + searchForm.getBasicSearchType() + " ? ");
          if(searchForm.isSearchable()){
            sqlStat2.append("AND E.ELEMENT_ID = ? ");
          }
          preStat2 = dbConn.prepareStatement(sqlStat2.toString());
          
          int parameterIndex = 1;
          this.setPrepareStatement(preStat2, parameterIndex++, FormElementType.ELEMENT_SELECTION_BOX);
          this.setPrepareStatement(preStat2, parameterIndex++, FormElementType.ELEMENT_RADIO_BUTTON);
          this.setPrepareStatement(preStat2, parameterIndex++, FormElementType.ELEMENT_CHECK_BOX);
          this.setPrepareStatement(preStat2, parameterIndex++, searchKeyword);  
          if(searchForm.isSearchable()){  
            this.setPrepareStatement(preStat2, parameterIndex++, searchField);
          }
            
            rs2= preStat2.executeQuery();
            String submissionID = "";
          while (rs2.next()) {
            submissionID += ((submissionID.length()>0)?",":"") + getResultSetInteger(rs2, "SUBMISSION_ID");
          }
          // For Select Box, Radio Button, Check Box
          sqlStat2 = new StringBuffer();
          sqlStat2.append("SELECT DISTINCT E.SUBMISSION_ID ");
          sqlStat2.append("FROM FORM_DATA_ELEMENT E, FORM_DATA D, FORM_SELECTION_FIELD F, FORM_SELECTION_FIELD_OPTION G ");
          sqlStat2.append("WHERE D.DATA_ELEMENT_ID = E.ID AND G.SELECTION_FIELD_ID = F.ID AND E.ELEMENT_ID = F.ELEMENT_ID AND D.DATA_STRING = G.START_VALUE ");
          sqlStat2.append("AND G.LABEL " + searchForm.getBasicSearchType() + " ? ");
          if(searchForm.isSearchable()){
            sqlStat2.append("AND E.ELEMENT_ID = ? ");
          }

          preStat2 = dbConn.prepareStatement(sqlStat2.toString());
          this.setPrepareStatement(preStat2, 1, searchKeyword);  
          if(searchForm.isSearchable()){  
            this.setPrepareStatement(preStat2, 2, searchField);
          }
          rs2= preStat2.executeQuery();
          while (rs2.next()) {
            submissionID += ((submissionID.length()>0)?",":"") + getResultSetInteger(rs2, "SUBMISSION_ID");
          }

          if (!Utility.isEmpty(submissionID)) {
            sqlStat.append("           AND C.ID IN ("+submissionID+") ");
          }else{
            sqlStat.append("           AND C.ID IN (-1) ");
          }
          //}
          try { rs2.close(); } catch (Exception ignore) {} finally { rs2 = null; }
          try { preStat2.close(); } catch (Exception ignore) {} finally { preStat2 = null; }
        }

        sqlStat.append(attachedString);
        sqlStat = this.getFormattedSQL(sqlStat.toString());

        // Form the ORDER clause for sorting.
        if (searchForm.isSortable()) {
          String sortAttribute = searchForm.getSortAttribute();
          if (sortAttribute.indexOf(".") < 0) {
            if ("TITLE".equals(sortAttribute)){
              sortAttribute = "UPDATE_DATE";
              searchForm.setSortAttribute("UPDATE_DATE");
              searchForm.setSortOrder("DESC");
            }
            sortAttribute = "C." + sortAttribute;             
          }       
          sqlStat.append("ORDER BY " + sortAttribute + " " + searchForm.getSortOrder());
        }

        // Get total number of record return.
        sqlStatCnt = this.getSelectCountSQL(sqlStat);
        preStatCnt = dbConn.prepareStatement(sqlStatCnt.toString());
        this.setPrepareStatement(preStatCnt, 1, GlobalConstant.RECORD_RELEASED);
        this.setPrepareStatement(preStatCnt, 2, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStatCnt, 3, formRecordID);

        rsCnt = preStatCnt.executeQuery();
        if (rsCnt.next()) {
          totalNumOfRecord = rsCnt.getInt(1);
        }

        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }

        // Retrieve the result in row basis.
        sqlStat = this.getSelectListSQL(sqlStat, startOffset, pageSize);
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_RELEASED);
        this.setPrepareStatement(preStat, 2, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 3, formRecordID);

        rs = preStat.executeQuery();

        this.positionCursor(rs, startOffset, pageSize);

        while (rs.next() && rowLoopCnt<pageSize) {
          FormSubmission tmpFormSubmission = new FormSubmission();

          tmpFormSubmission.setFormCode(getResultSetString(rs, "FORM_CODE"));
          tmpFormSubmission.setFormVersion(getResultSetString(rs, "FORM_VERSION"));
          tmpFormSubmission.setTitle(getResultSetString(rs, "TITLE"));
          tmpFormSubmission.setID(getResultSetInteger(rs, "ID"));
          tmpFormSubmission.setTrackID(getResultSetInteger(rs, "TRACK_ID"));
          tmpFormSubmission.setFormRecordID(getResultSetInteger(rs, "FORM_RECORD_ID"));
          tmpFormSubmission.setWorkflowRecordID(getResultSetInteger(rs, "WORKFLOW_RECORD_ID"));
          tmpFormSubmission.setWorkflowEndDate(getResultSetTimestamp(rs, "WORKFLOW_END_DATE"));
          tmpFormSubmission.setIp(getResultSetString(rs, "IP"));
          tmpFormSubmission.setGuestName(getResultSetString(rs, "GUEST_NAME"));
          tmpFormSubmission.setEmail(getResultSetString(rs, "EMAIL"));
          tmpFormSubmission.setContactInfo(getResultSetString(rs, "CONTACT_INFO"));
          tmpFormSubmission.setDmsParentID(getResultSetInteger(rs, "DMS_PARENT_ID"));
          tmpFormSubmission.setStatus(getResultSetString(rs, "STATUS"));
          tmpFormSubmission.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormSubmission.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormSubmission.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormSubmission.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpFormSubmission.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpFormSubmission.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpFormSubmission.setCreatorName(UserInfoFactory.getUserFullName(tmpFormSubmission.getCreatorID()));
          tmpFormSubmission.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormSubmission.getUpdaterID()));
          tmpFormSubmission.setRecordCount(totalNumOfRecord);

          // Retrive the workflow relationship.         
          com.dcivision.workflow.dao.MtmWorkflowProgressSystemObjectDAObject mtmWfProgressSysObjDAO = new com.dcivision.workflow.dao.
					MtmWorkflowProgressSystemObjectDAObject(sessionContainer, dbConn);
          com.dcivision.workflow.dao.WorkflowRecordDAObject workflowRecordDAO = new com.dcivision.workflow.dao.WorkflowRecordDAObject(sessionContainer, dbConn);
          
          List tmpList = mtmWfProgressSysObjDAO.getListByBeanClassNameObjectID(tmpFormSubmission.getClass().getName(), getResultSetInteger(rs, "ID"));
          List workflowRelationshipList = new ArrayList();
          
          if(tmpList.size()>0){
          	com.dcivision.workflow.bean.MtmWorkflowProgressSystemObject tmpObj = (com.dcivision.workflow.bean.MtmWorkflowProgressSystemObject)tmpList.get(0);
          	com.dcivision.workflow.bean.WorkflowRecord wfRec = (com.dcivision.workflow.bean.WorkflowRecord)workflowRecordDAO.getObjectByTrackID(tmpObj.getTrackID());
          	if (wfRec != null) {
          		workflowRelationshipList.add(new Object[] {wfRec, tmpObj.getTrackID()});
          	}
          	tmpFormSubmission.setWorkflowRelationshipList(workflowRelationshipList);
          }
          mtmWfProgressSysObjDAO=null;
          workflowRecordDAO=null;
          

          tmpFormSubmission.setRowNum(startOffset++);
          ++rowLoopCnt;
          result.add(tmpFormSubmission);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }
      }
    }
  }
  
  /**
   * Get Submission List
   * @param searchForm
   * @return
   * @throws ApplicationException
   */
  public synchronized List getFormSubmissionListBySearchSection(
      AbstractSearchForm searchForm)
      throws ApplicationException {
    String formRecordID = ((ListFormSubmissionForm)searchForm).getFormRecordID();
    ListFormSubmissionForm listFormSubmissionForm = (ListFormSubmissionForm)searchForm;
    PreparedStatement preStat = null;
    PreparedStatement preStat2 = null;
    PreparedStatement preStatCnt = null;
    ResultSet rs = null;
    ResultSet rs2 = null;
    ResultSet rsCnt = null;
    StringBuffer sqlStat = new StringBuffer();
    StringBuffer sqlStatCnt = new StringBuffer();
    List result = new ArrayList();
    int totalNumOfRecord = 0;
    int rowLoopCnt = 0;
    int startOffset = (TextUtility.parseInteger(listFormSubmissionForm.getCurSubmissionStartRowNo()));
    int pageSize = TextUtility.parseInteger(searchForm.getPageOffset());

    String fromDate = listFormSubmissionForm.getFromDate();
    String toDate = TextUtility.dbDateAdder(listFormSubmissionForm.getToDate(), 1);
    String attachedString = "";
    String basicSearchKeyword = listFormSubmissionForm.getBasicSearchKeyword();
    String searchSubmitter = listFormSubmissionForm.getSearchSubmitter();
    StringBuffer sqlStat2 = new StringBuffer();
    String workflowRecordID = listFormSubmissionForm.getWorkflowRecordID();


    if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_ORACLE) {
        if (!Utility.isEmpty(fromDate) && Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE >= TO_DATE('" + fromDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      } else if (Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE <= TO_DATE('" + toDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      } else if (!Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE BETWEEN TO_DATE('" + fromDate + "', 'YYYY-MM-DD HH24:MI:SS') AND TO_DATE('"+  toDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      }
    } else {
        if (!Utility.isEmpty(fromDate) && Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE >= '" + fromDate + "' ";
      } else if (Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE <= '" + toDate + "' ";
      } else if (!Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE BETWEEN '" + fromDate + "' AND '"+  toDate + "' ";
      }
    }

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.FORM_CODE, A.FORM_VERSION, A.TITLE,C.ID, C.TRACK_ID, C.FORM_RECORD_ID, C.WORKFLOW_RECORD_ID, C.IP,C.GUEST_NAME,C.EMAIL,C.CONTACT_INFO, C.DMS_PARENT_ID, C.STATUS,C.RECORD_STATUS,C.UPDATE_COUNT, C.CREATOR_ID, C.CREATE_DATE, C.UPDATER_ID,C.UPDATE_DATE, WR.END_DATE WORKFLOW_END_DATE ");
        sqlStat.append("FROM   FORM_RECORD A  INNER JOIN FORM_SUBMISSION C ON A.ID = C.FORM_RECORD_ID ");
        sqlStat.append("LEFT JOIN WORKFLOW_RECORD WR ON WR.ID = C.WORKFLOW_RECORD_ID ");
        sqlStat.append("WHERE  A.STATUS = ? AND C.RECORD_STATUS = ? AND C.FORM_RECORD_ID = ? ");
        sqlStat.append("AND C.CREATOR_ID = '"+ sessionContainer.getUserRecordID() +"' ");
        sqlStat.append("AND C.STATUS <> '" + FormSubmission.FORM_SUBMISSION_STATU_SAVED + "' ");
        if (!Utility.isEmpty(workflowRecordID) && !"null".equals(workflowRecordID)){
          sqlStat.append("AND C.WORKFLOW_RECORD_ID = " + workflowRecordID + " ");
        } else {
          sqlStat.append("AND C.WORKFLOW_RECORD_ID IS NULL ");
        }
          
       
        if(!Utility.isEmpty(basicSearchKeyword)){
          // For Text Box
          sqlStat2.append("SELECT DISTINCT E.SUBMISSION_ID FROM FORM_DATA_ELEMENT E, FORM_DATA D, FORM_ELEMENT FE ");
          sqlStat2.append("WHERE D.DATA_ELEMENT_ID = E.ID ");
          sqlStat2.append(" AND E.ELEMENT_ID = FE.ID \n");
          sqlStat2.append(" AND FE.ELEMENT_TYPE <> ? \n");
          sqlStat2.append(" AND FE.ELEMENT_TYPE <> ? \n");
          sqlStat2.append(" AND FE.ELEMENT_TYPE <> ? \n");
          String searchField = searchForm.getBasicSearchField();
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          sqlStat2.append("AND D.DATA_STRING " + searchForm.getBasicSearchType() + " ? ");
          if(searchForm.isSearchable()){
            sqlStat2.append("AND E.ELEMENT_ID = ? ");
          }
          preStat2 = dbConn.prepareStatement(sqlStat2.toString());
          
          int parameterIndex = 1;
          this.setPrepareStatement(preStat2, parameterIndex++, FormElementType.ELEMENT_SELECTION_BOX);
          this.setPrepareStatement(preStat2, parameterIndex++, FormElementType.ELEMENT_RADIO_BUTTON);
          this.setPrepareStatement(preStat2, parameterIndex++, FormElementType.ELEMENT_CHECK_BOX);
          this.setPrepareStatement(preStat2, parameterIndex++, searchKeyword);
          if(searchForm.isSearchable()){  
            this.setPrepareStatement(preStat2, parameterIndex++, searchField);
          }
            
            rs2= preStat2.executeQuery();
            String submissionID = "";
          while (rs2.next()) {
            submissionID += ((submissionID.length()>0)?",":"") + getResultSetInteger(rs2, "SUBMISSION_ID");
          }
          // For Select Box, Radio Button, Check Box
          sqlStat2 = new StringBuffer();
          sqlStat2.append("SELECT DISTINCT E.SUBMISSION_ID ");
          sqlStat2.append("FROM FORM_DATA_ELEMENT E, FORM_DATA D, FORM_SELECTION_FIELD F, FORM_SELECTION_FIELD_OPTION G ");
          sqlStat2.append("WHERE D.DATA_ELEMENT_ID = E.ID AND G.SELECTION_FIELD_ID = F.ID AND E.ELEMENT_ID = F.ELEMENT_ID AND D.DATA_STRING = G.START_VALUE ");
          sqlStat2.append("AND G.LABEL " + searchForm.getBasicSearchType() + " ? ");
          if(searchForm.isSearchable()){
            sqlStat2.append("AND E.ELEMENT_ID = ? ");
          }

          preStat2 = dbConn.prepareStatement(sqlStat2.toString());
          this.setPrepareStatement(preStat2, 1, searchKeyword);  
          if(searchForm.isSearchable()){  
            this.setPrepareStatement(preStat2, 2, searchField);
          }
          rs2= preStat2.executeQuery();
          while (rs2.next()) {
            submissionID += ((submissionID.length()>0)?",":"") + getResultSetInteger(rs2, "SUBMISSION_ID");
          }

          if (!Utility.isEmpty(submissionID)) {
            sqlStat.append("           AND C.ID IN ("+submissionID+") ");
          }else{
            sqlStat.append("           AND C.ID IN (-1) ");
          }
          //}
          try { rs2.close(); } catch (Exception ignore) {} finally { rs2 = null; }
          try { preStat2.close(); } catch (Exception ignore) {} finally { preStat2 = null; }
        }

        sqlStat.append(attachedString);
        sqlStat = this.getFormattedSQL(sqlStat.toString());

        // Form the ORDER clause for sorting.
        if (searchForm.isSortable()) {
          String sortAttribute = listFormSubmissionForm.getSubmitSortAttribute();
          if (sortAttribute.indexOf(".") < 0) {
            if ("TITLE".equals(sortAttribute)){
              sortAttribute = "UPDATE_DATE";
              listFormSubmissionForm.setSubmitSortOrder("DESC");
            }
            sortAttribute = "C." + sortAttribute;             
          }
          sqlStat.append("ORDER BY " + sortAttribute + " " + listFormSubmissionForm.getSubmitSortOrder());
        }

        // Get total number of record return.
        sqlStatCnt = this.getSelectCountSQL(sqlStat);
        preStatCnt = dbConn.prepareStatement(sqlStatCnt.toString());
        this.setPrepareStatement(preStatCnt, 1, GlobalConstant.RECORD_RELEASED);
        this.setPrepareStatement(preStatCnt, 2, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStatCnt, 3, formRecordID);

        rsCnt = preStatCnt.executeQuery();
        if (rsCnt.next()) {
          totalNumOfRecord = rsCnt.getInt(1);
        }

        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }

        // Retrieve the result in row basis.
        sqlStat = this.getSelectListSQL(sqlStat, startOffset, pageSize);
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_RELEASED);
        this.setPrepareStatement(preStat, 2, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 3, formRecordID);

        rs = preStat.executeQuery();

        this.positionCursor(rs, startOffset, pageSize);

        while (rs.next() && rowLoopCnt<pageSize) {
          FormSubmission tmpFormSubmission = new FormSubmission();

          tmpFormSubmission.setFormCode(getResultSetString(rs, "FORM_CODE"));
          tmpFormSubmission.setFormVersion(getResultSetString(rs, "FORM_VERSION"));
          tmpFormSubmission.setTitle(getResultSetString(rs, "TITLE"));
          tmpFormSubmission.setID(getResultSetInteger(rs, "ID"));
          tmpFormSubmission.setTrackID(getResultSetInteger(rs, "TRACK_ID"));
          tmpFormSubmission.setFormRecordID(getResultSetInteger(rs, "FORM_RECORD_ID"));
          tmpFormSubmission.setWorkflowRecordID(getResultSetInteger(rs, "WORKFLOW_RECORD_ID"));
          tmpFormSubmission.setWorkflowEndDate(getResultSetTimestamp(rs, "WORKFLOW_END_DATE"));
          tmpFormSubmission.setIp(getResultSetString(rs, "IP"));
          tmpFormSubmission.setGuestName(getResultSetString(rs, "GUEST_NAME"));
          tmpFormSubmission.setEmail(getResultSetString(rs, "EMAIL"));
          tmpFormSubmission.setContactInfo(getResultSetString(rs, "CONTACT_INFO"));
          tmpFormSubmission.setDmsParentID(getResultSetInteger(rs, "DMS_PARENT_ID"));
          tmpFormSubmission.setStatus(getResultSetString(rs, "STATUS"));
          tmpFormSubmission.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormSubmission.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormSubmission.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormSubmission.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpFormSubmission.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpFormSubmission.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpFormSubmission.setCreatorName(UserInfoFactory.getUserFullName(tmpFormSubmission.getCreatorID()));
          tmpFormSubmission.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormSubmission.getUpdaterID()));
          tmpFormSubmission.setSubmissionRecordCount(totalNumOfRecord);
          tmpFormSubmission.setRecordCount(totalNumOfRecord);
          // Retrive the workflow relationship.         
          com.dcivision.workflow.dao.MtmWorkflowProgressSystemObjectDAObject mtmWfProgressSysObjDAO = new com.dcivision.workflow.dao.
                    MtmWorkflowProgressSystemObjectDAObject(sessionContainer, dbConn);
          com.dcivision.workflow.dao.WorkflowRecordDAObject workflowRecordDAO = new com.dcivision.workflow.dao.WorkflowRecordDAObject(sessionContainer, dbConn);
          
          List tmpList = mtmWfProgressSysObjDAO.getListByBeanClassNameObjectID(tmpFormSubmission.getClass().getName(), getResultSetInteger(rs, "ID"));
          List workflowRelationshipList = new ArrayList();
          
          if(tmpList.size()>0){
            com.dcivision.workflow.bean.MtmWorkflowProgressSystemObject tmpObj = (com.dcivision.workflow.bean.MtmWorkflowProgressSystemObject)tmpList.get(0);
            com.dcivision.workflow.bean.WorkflowRecord wfRec = (com.dcivision.workflow.bean.WorkflowRecord)workflowRecordDAO.getObjectByTrackID(tmpObj.getTrackID());
            if (wfRec != null) {
                workflowRelationshipList.add(new Object[] {wfRec, tmpObj.getTrackID()});
            }
            tmpFormSubmission.setWorkflowRelationshipList(workflowRelationshipList);
          }
          mtmWfProgressSysObjDAO=null;
          workflowRecordDAO=null;
          

          tmpFormSubmission.setRowNum(startOffset++);
          ++rowLoopCnt;
          result.add(tmpFormSubmission);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }
      }
    }
  }
  
  /**
   * get the form submission list by the search section for Tracking
   * @param searchForm
   * @return
   * @throws ApplicationException
   */
  public synchronized List getFormSubmissionListBySearchSectionForTracking(
      AbstractSearchForm searchForm )
      throws ApplicationException {
    ListFormSubmissionForm listFormSubmissionForm = (ListFormSubmissionForm)searchForm;
    List result = new ArrayList();
    if (Utility.isEmpty(listFormSubmissionForm.getSearchFormDisplayType()) || "null".equals(listFormSubmissionForm.getSearchFormDisplayType())){
      result = this.getFormSubmissionListBySearchSection(searchForm,true);
    }else{
      result = this.getFormSubmissionWholeFormListBySearchSection(searchForm,true);
    }
    return (result);    
  }

  /**
   * get the form submission list by the search section for Monitoring
   * @param searchForm
   * @return
   * @throws ApplicationException
   */
  public synchronized List getFormSubmissionListBySearchSectionForMonitoring(
      AbstractSearchForm searchForm )
      throws ApplicationException {
    ListFormSubmissionForm listFormSubmissionForm = (ListFormSubmissionForm)searchForm;
    List result = new ArrayList();
    if (Utility.isEmpty(listFormSubmissionForm.getSearchFormDisplayType()) || "null".equals(listFormSubmissionForm.getSearchFormDisplayType())){
      result = this.getFormSubmissionListBySearchSection(searchForm,false);
    }else{
      result = this.getFormSubmissionWholeFormListBySearchSection(searchForm,false);
    }
    return (result);
  }

  public synchronized List getNullListByReport(AbstractSearchForm searchForm) throws ApplicationException {
    return this.getReleasedFormList(searchForm);
  }

  /**
   * Get the released Form list
   * @param searchForm
   * @return Form Record List
   * @throws ApplicationException
   */
  public synchronized List getReleasedFormList(AbstractSearchForm searchForm)
      throws ApplicationException {
    PreparedStatement preStat = null;
    PreparedStatement preStatCnt = null;
    ResultSet rs = null;
    ResultSet rsCnt = null;
    StringBuffer sqlStat = new StringBuffer();
    StringBuffer sqlStatCnt = new StringBuffer();
    List result = new ArrayList();
    int totalNumOfRecord = 0;
    int rowLoopCnt = 0;
    int startOffset = TextUtility.parseInteger(searchForm.getCurStartRowNo());
    int pageSize = TextUtility.parseInteger(searchForm.getPageOffset());
    ListFormRecordForm actionForm = (ListFormRecordForm)searchForm;
    Integer formGroupID = actionForm.getFormGroupID();
    
    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.FORM_CODE, A.FORM_VERSION, A.FORM_TYPE, A.TITLE, A.TITLE_ALT, A.DESCRIPTION, A.DESCRIPTION_ALT, A.STATUS, A.FORM_CATEGORY_ID, A.TRACK_CLASS, A.SUBMISSION_CLASS, A.AUTO_NUMBERING, A.LAST_PAGE_CODE, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   FORM_RECORD A, FORM_SUBMISSION C ");
        sqlStat.append("WHERE  A.ID = C.FORM_RECORD_ID AND A.STATUS = ? AND A.RECORD_STATUS = ? ");
        sqlStat.append("AND A.RECORD_STATUS = C.RECORD_STATUS AND C.STATUS <> ? ");
        sqlStat.append("AND A.FORM_GROUP_ID = " + formGroupID + " ");
        // Form the WHERE clause for filtering.
        if (searchForm.isSearchable()) {
          String searchField = getSearchColumn(searchForm.getBasicSearchField());
          sqlStat.append("AND  " + searchField + " " + searchForm.getBasicSearchType() + " ? ");
        }
        if (!Utility.isEmpty(actionForm.getSearchFormType())){
          sqlStat.append("AND A.FORM_TYPE = '" + actionForm.getSearchFormType() + "' ");
        }
        
        sqlStat.append("GROUP BY A.ID, A.FORM_CODE, A.FORM_VERSION, A.FORM_TYPE, A.TITLE, A.TITLE_ALT, A.DESCRIPTION, A.DESCRIPTION_ALT, A.STATUS, A.FORM_CATEGORY_ID, A.TRACK_CLASS, A.SUBMISSION_CLASS, A.AUTO_NUMBERING, A.LAST_PAGE_CODE, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");

        //format the sql for any 'LIKE' statement contained
        sqlStat = this.getFormattedSQL(sqlStat.toString());

        // Form the ORDER clause for sorting.
        if (searchForm.isSortable()) {
          String sortAttribute = searchForm.getSortAttribute();
          if (sortAttribute.indexOf(".") < 0) {
            sortAttribute = "A." + sortAttribute;
          }
          sqlStat.append("ORDER BY " + sortAttribute + " " + searchForm.getSortOrder());
        }

        // Get total number of record return.
        sqlStatCnt = this.getSelectCountSQL(sqlStat);
        preStatCnt = dbConn.prepareStatement(sqlStatCnt.toString());
        this.setPrepareStatement(preStatCnt, 1, GlobalConstant.RECORD_RELEASED);
        this.setPrepareStatement(preStatCnt, 2, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStatCnt, 3, FormSubmission.FORM_SUBMISSION_STATU_SAVED);
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          this.setPrepareStatement(preStatCnt, 4, searchKeyword);
        }

        rsCnt = preStatCnt.executeQuery();
        while (rsCnt.next()) {
          //totalNumOfRecord = rsCnt.getInt(1);
          totalNumOfRecord ++;
        }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }

        // Retrieve the result in row basis.
        sqlStat = this.getSelectListSQL(sqlStat, startOffset, pageSize);
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_RELEASED);
        this.setPrepareStatement(preStat, 2, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 3, FormSubmission.FORM_SUBMISSION_STATU_SAVED);
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          this.setPrepareStatement(preStat, 4, searchKeyword);
        }

        rs = preStat.executeQuery();

        this.positionCursor(rs, startOffset, pageSize);

        while (rs.next() && rowLoopCnt<pageSize) {
          FormRecord tmpFormRecord = new FormRecord();
          tmpFormRecord.setID(getResultSetInteger(rs, "ID"));
          tmpFormRecord.setFormCode(getResultSetString(rs, "FORM_CODE"));
          tmpFormRecord.setFormVersion(getResultSetString(rs, "FORM_VERSION"));
          tmpFormRecord.setFormType(getResultSetInteger(rs, "FORM_TYPE"));
          tmpFormRecord.setTitle(getResultSetString(rs, "TITLE"));
          tmpFormRecord.setTitleAlt(getResultSetString(rs, "TITLE_ALT"));
          tmpFormRecord.setDescription(getResultSetString(rs, "DESCRIPTION"));
          tmpFormRecord.setDescriptionAlt(getResultSetString(rs, "DESCRIPTION_ALT"));
          tmpFormRecord.setStatus(getResultSetString(rs, "STATUS"));
          tmpFormRecord.setFormCategoryID(getResultSetInteger(rs, "FORM_CATEGORY_ID"));
//          tmpFormRecord.setFormCategory(getResultSetString(rs, "FORM_CATEGORY_NAME"));
          tmpFormRecord.setTrackClass(getResultSetString(rs, "TRACK_CLASS"));
          tmpFormRecord.setSubmissionClass(getResultSetString(rs, "SUBMISSION_CLASS"));
          tmpFormRecord.setAutoNumbering(getResultSetString(rs, "AUTO_NUMBERING"));
          tmpFormRecord.setLastPageCode(getResultSetString(rs, "LAST_PAGE_CODE"));
          tmpFormRecord.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormRecord.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormRecord.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormRecord.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpFormRecord.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpFormRecord.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpFormRecord.setCreatorName(UserInfoFactory.getUserFullName(tmpFormRecord.getCreatorID()));
          tmpFormRecord.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormRecord.getUpdaterID()));
          tmpFormRecord.setRecordCount(totalNumOfRecord);
          tmpFormRecord.setRowNum(startOffset++);
          ++rowLoopCnt;
          result.add(tmpFormRecord);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }
      }
    }
  }

  /**
   * Get the number of submissions For Report List
   * @param formRecordID
   * @return
   * @throws ApplicationException
   */
  public synchronized Integer getNoOfActiveRecordForReportByFormRecordID(
      Integer formRecordID)
      throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();

    PreparedStatement preStat1 = null;
    ResultSet rs1 = null;
    StringBuffer sqlStat1 = new StringBuffer();
    synchronized(dbConn) {
      try {

        sqlStat.append("SELECT COUNT(*) as NO_OF_ACTIVE_RECORDS ");
        sqlStat.append("FROM   FORM_SUBMISSION A ");
        sqlStat.append("WHERE  A.FORM_RECORD_ID = ? AND A.RECORD_STATUS = ? AND A.STATUS <> ? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, formRecordID);
        this.setPrepareStatement(preStat, 2, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 3, FormSubmission.FORM_SUBMISSION_STATU_SAVED);
        rs = preStat.executeQuery();
        if (rs.next()) {
          return(getResultSetInteger(rs, "NO_OF_ACTIVE_RECORDS"));
        } else {
          throw new ApplicationException(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  public synchronized AbstractBaseObject getLastUpdateFormSubmissionByFormRecordID(Integer formRecordID) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.TRACK_ID, A.FORM_RECORD_ID, A.WORKFLOW_RECORD_ID, A.IP, A.GUEST_NAME, A.EMAIL, A.CONTACT_INFO, A.DMS_PARENT_ID, A.STATUS, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   FORM_SUBMISSION A ");
        sqlStat.append("WHERE  A.FORM_RECORD_ID = ? AND A.RECORD_STATUS = ? AND A.STATUS <> ? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, formRecordID);
        this.setPrepareStatement(preStat, 2, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 3, FormSubmission.FORM_SUBMISSION_STATU_SAVED);
        rs = preStat.executeQuery();
        FormSubmission tmpFormSubmission = new FormSubmission();
        if (rs.next()) {
          tmpFormSubmission.setID(getResultSetInteger(rs, "ID"));
          tmpFormSubmission.setTrackID(getResultSetInteger(rs, "TRACK_ID"));
          tmpFormSubmission.setFormRecordID(getResultSetInteger(rs, "FORM_RECORD_ID"));
          tmpFormSubmission.setWorkflowRecordID(getResultSetInteger(rs, "WORKFLOW_RECORD_ID"));
          tmpFormSubmission.setIp(getResultSetString(rs, "IP"));
          tmpFormSubmission.setGuestName(getResultSetString(rs, "GUEST_NAME"));
          tmpFormSubmission.setEmail(getResultSetString(rs, "EMAIL"));
          tmpFormSubmission.setContactInfo(getResultSetString(rs, "CONTACT_INFO"));
          tmpFormSubmission.setDmsParentID(getResultSetInteger(rs, "DMS_PARENT_ID"));
          tmpFormSubmission.setStatus(getResultSetString(rs, "STATUS"));
          tmpFormSubmission.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormSubmission.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormSubmission.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormSubmission.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpFormSubmission.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpFormSubmission.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpFormSubmission.setCreatorName(UserInfoFactory.getUserFullName(tmpFormSubmission.getCreatorID()));
          tmpFormSubmission.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormSubmission.getUpdaterID()));
          result.add(tmpFormSubmission);
        }
        return(tmpFormSubmission);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  /**
   * Get the report summary by form ID
   * @param searchForm
   * @return
   * @throws ApplicationException
   */
  public synchronized List getReportSummaryByFormID(
      AbstractSearchForm searchForm)
      throws ApplicationException {
    String formRecordID = ((ListFormSubmissionForm)searchForm).getFormRecordID();
    PreparedStatement preStat = null;
    PreparedStatement preStatCnt = null;
    ResultSet rs = null;
    ResultSet rsCnt = null;
    StringBuffer sqlStat = new StringBuffer();
    StringBuffer sqlStatCnt = new StringBuffer();
    List result = new ArrayList();
    int totalNumOfRecord = 0;
    int rowLoopCnt = 0;
    int startOffset = TextUtility.parseInteger(searchForm.getCurStartRowNo());
    int pageSize = TextUtility.parseInteger(searchForm.getPageOffset());
    //String formRecordID = ((ListFormSubmissionForm)searchForm).getBasicSelectedID();

    synchronized(dbConn) {
      try {
//        sqlStat.append("SELECT A.FORM_CODE, A.FORM_VERSION, A.TITLE,C.ID, C.FORM_RECORD_ID,C.IP,C.GUEST_NAME,C.EMAIL,C.CONTACT_INFO,C.STATUS,C.RECORD_STATUS,C.UPDATE_COUNT, C.CREATOR_ID, C.CREATE_DATE, C.UPDATER_ID,C.UPDATE_DATE,B.FORM_CATEGORY_NAME ");
//        sqlStat.append("FROM   FORM_RECORD A, SETUP_OPTION_FORM_CATEGORY B , FORM_SUBMISSION C ");
//        sqlStat.append("WHERE  A.FORM_CATEGORY_ID = B.ID AND A.ID = C.FORM_RECORD_ID AND A.STATUS = ? AND C.RECORD_STATUS = ? AND C.CREATOR_ID = ? AND C.FORM_RECORD_ID = ? ");
        sqlStat.append("SELECT A.FORM_CODE, A.FORM_VERSION, A.TITLE,C.ID, C.TRACK_ID, C.FORM_RECORD_ID, C.WORKFLOW_RECORD_ID, C.IP,C.GUEST_NAME,C.EMAIL,C.CONTACT_INFO, C.DMS_PARENT_ID, C.STATUS,C.RECORD_STATUS,C.UPDATE_COUNT, C.CREATOR_ID, C.CREATE_DATE, C.UPDATER_ID,C.UPDATE_DATE ");
        sqlStat.append("FROM   FORM_RECORD A, FORM_SUBMISSION C ");
        sqlStat.append("WHERE  A.ID = C.FORM_RECORD_ID AND A.STATUS = ? AND C.RECORD_STATUS = ? AND C.CREATOR_ID = ? AND C.FORM_RECORD_ID = ? ");

        // Form the WHERE clause for filtering.
        if (searchForm.isSearchable()) {
          String searchField = getSearchColumn(searchForm.getBasicSearchField());
          sqlStat.append("AND  " + searchField + " " + searchForm.getBasicSearchType() + " ? ");
        }

        //format the sql for any 'LIKE' statement contained
        sqlStat = this.getFormattedSQL(sqlStat.toString());

        // Form the ORDER clause for sorting.
        if (searchForm.isSortable()) {
          String sortAttribute = searchForm.getSortAttribute();
          if (sortAttribute.indexOf(".") < 0) {
            sortAttribute = "A." + sortAttribute;
          }
          sqlStat.append("ORDER BY " + sortAttribute + " " + searchForm.getSortOrder());
        }

        // Get total number of record return.
        sqlStatCnt = this.getSelectCountSQL(sqlStat);
        preStatCnt = dbConn.prepareStatement(sqlStatCnt.toString());
        this.setPrepareStatement(preStatCnt, 1, GlobalConstant.RECORD_RELEASED);
        this.setPrepareStatement(preStatCnt, 2, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStatCnt, 3, sessionContainer.getUserRecordID());
        this.setPrepareStatement(preStatCnt, 4, formRecordID);
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          this.setPrepareStatement(preStatCnt, 5, searchKeyword);
        }

        rsCnt = preStatCnt.executeQuery();
        if (rsCnt.next()) {
          totalNumOfRecord = rsCnt.getInt(1);
        }

        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }

        // Retrieve the result in row basis.
        sqlStat = this.getSelectListSQL(sqlStat, startOffset, pageSize);
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_RELEASED);
        this.setPrepareStatement(preStat, 2, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 3, sessionContainer.getUserRecordID());
        this.setPrepareStatement(preStat, 4, formRecordID);
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          this.setPrepareStatement(preStat, 5, searchKeyword);
        }

        rs = preStat.executeQuery();

        this.positionCursor(rs, startOffset, pageSize);



        while (rs.next() && rowLoopCnt<pageSize) {
          FormSubmission tmpFormSubmission = new FormSubmission();

          tmpFormSubmission.setFormCode(getResultSetString(rs, "FORM_CODE"));
          tmpFormSubmission.setFormVersion(getResultSetString(rs, "FORM_VERSION"));
          tmpFormSubmission.setTitle(getResultSetString(rs, "TITLE"));
          tmpFormSubmission.setID(getResultSetInteger(rs, "ID"));
          tmpFormSubmission.setTrackID(getResultSetInteger(rs, "TRACK_ID"));
          tmpFormSubmission.setFormRecordID(getResultSetInteger(rs, "FORM_RECORD_ID"));
          tmpFormSubmission.setWorkflowRecordID(getResultSetInteger(rs, "WORKFLOW_RECORD_ID"));
          tmpFormSubmission.setIp(getResultSetString(rs, "IP"));
          tmpFormSubmission.setGuestName(getResultSetString(rs, "GUEST_NAME"));
          tmpFormSubmission.setEmail(getResultSetString(rs, "EMAIL"));
          tmpFormSubmission.setContactInfo(getResultSetString(rs, "CONTACT_INFO"));
          tmpFormSubmission.setDmsParentID(getResultSetInteger(rs, "DMS_PARENT_ID"));
          tmpFormSubmission.setStatus(getResultSetString(rs, "STATUS"));
          tmpFormSubmission.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormSubmission.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormSubmission.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormSubmission.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpFormSubmission.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpFormSubmission.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpFormSubmission.setCreatorName(UserInfoFactory.getUserFullName(tmpFormSubmission.getCreatorID()));
          tmpFormSubmission.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormSubmission.getUpdaterID()));
          tmpFormSubmission.setRecordCount(totalNumOfRecord);
          tmpFormSubmission.setRowNum(startOffset++);
          ++rowLoopCnt;
          result.add(tmpFormSubmission);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }
      }
    }
  }

  /**
   * Get all submitted form list
   * @param searchForm
   * @return
   * @throws ApplicationException
   */
  public synchronized List getNullListByFormMonitor(AbstractSearchForm searchForm) throws ApplicationException {
    return this.getSubmittedFormList(searchForm,true);
  }

  /**
   * Get submitted form list
   * @param searchForm
   * @return
   * @throws ApplicationException
   */
  public synchronized List getSubmittedFormList(AbstractSearchForm searchForm,
                                                boolean isPersonal)
      throws ApplicationException {
    PreparedStatement preStat = null;
    PreparedStatement preStatCnt = null;
    PreparedStatement preStatTmp = null;
    ResultSet rs = null;
    ResultSet rsTmp = null;
    ResultSet rsCnt = null;
    StringBuffer sqlStat = new StringBuffer();
    StringBuffer sqlStatTmp = new StringBuffer();
    StringBuffer sqlStatCnt = new StringBuffer();
    
    List result = new ArrayList();
    int totalNumOfRecord = 0;
    int rowLoopCnt = 0;
    int startOffset = TextUtility.parseInteger(searchForm.getCurStartRowNo());
    int pageSize = TextUtility.parseInteger(searchForm.getPageOffset());
    ListFormSubmissionForm actionForm = (ListFormSubmissionForm)searchForm;
    String formRecordID = "";
    WorkflowRecordDAObject wfRecordDAO = new WorkflowRecordDAObject(this.sessionContainer, this.dbConn);
    
    synchronized(dbConn) {

      try {
        
      	if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_MYSQL) {
      		sqlStat.append("SELECT A.FORM_CODE, A.FORM_VERSION, A.TITLE, A.FORM_DOC_ID, A.FORM_GROUP_ID, C.ID, C.TRACK_ID, C.FORM_RECORD_ID, C.WORKFLOW_RECORD_ID, C.IP,C.GUEST_NAME,C.EMAIL,C.CONTACT_INFO, C.DMS_PARENT_ID, C.STATUS,C.RECORD_STATUS,C.UPDATE_COUNT, C.CREATOR_ID, C.CREATE_DATE, C.UPDATER_ID,MAX(C.UPDATE_DATE) UPDATE_DATE ");
      	} else {
      		sqlStat.append("SELECT A.FORM_CODE, A.FORM_VERSION, A.TITLE, A.FORM_DOC_ID, A.FORM_GROUP_ID, C.ID, C.TRACK_ID, C.FORM_RECORD_ID, C.WORKFLOW_RECORD_ID, C.IP,C.GUEST_NAME,C.EMAIL,C.CONTACT_INFO, C.DMS_PARENT_ID, C.STATUS,C.RECORD_STATUS,C.UPDATE_COUNT, C.CREATOR_ID, C.CREATE_DATE, C.UPDATER_ID,C.UPDATE_DATE ");      		
      	}
      	sqlStat.append("FROM   FORM_RECORD A, FORM_SUBMISSION C ");
        sqlStat.append("WHERE  A.ID = C.FORM_RECORD_ID ");
        sqlStat.append("AND A.STATUS = ? AND A.RECORD_STATUS = C.RECORD_STATUS AND C.RECORD_STATUS = ? ");       
        if (!Utility.isEmpty(((ListFormSubmissionForm)searchForm).getFormGroupID())){
          sqlStat.append("AND A.FORM_GROUP_ID = " + ((ListFormSubmissionForm)searchForm).getFormGroupID() + " ");
        }
        if (isPersonal) {
          //user can view form:1.submiter is user. 2.if user is not submit,but save the form in wf
          sqlStatTmp.append("SELECT DISTINCT FR.ID, FR.FORM_CODE ");
          sqlStatTmp.append("FROM FORM_RECORD FR, FORM_SUBMISSION C, MTM_WF_RECORD_OBJECT_LINK MWROL, WORKFLOW_PROGRESS WP ");
          sqlStatTmp.append("WHERE FR.ID = MWROL.OBJECT_ID AND C.FORM_RECORD_ID = FR.ID AND WP.TRACK_ID = C.TRACK_ID ");
          sqlStatTmp.append("AND WP.UPDATER_ID = '"+sessionContainer.getUserRecordID()+"' ");         
          preStatTmp = dbConn.prepareStatement(sqlStatTmp.toString());
          rsTmp = preStatTmp.executeQuery();
          while (rsTmp.next()){
            formRecordID += ((formRecordID.length()>0)?",":"") + getResultSetInteger(rsTmp, "ID");
          }
          sqlStat.append(" AND (C.CREATOR_ID = '"+sessionContainer.getUserRecordID()+"' "); // submiter is user
          if (!Utility.isEmpty(formRecordID)) {
            sqlStat.append("OR A.ID IN ("+formRecordID+") ) ");
          }else{
            sqlStat.append(" ) "); 
          }
        }else{
          sqlStat.append("AND C.STATUS <> '"+FormSubmission.FORM_SUBMISSION_STATU_SAVED+"' ");   
        }

        // Form the WHERE clause for filtering.
        if (searchForm.isSearchable()) {
          String searchField = getSearchColumn(searchForm.getBasicSearchField());
          sqlStat.append("AND  " + searchField + " " + searchForm.getBasicSearchType() + " ? ");
        }
        if (!Utility.isEmpty(actionForm.getSearchFormType())){
          sqlStat.append("AND A.FORM_TYPE = '" + actionForm.getSearchFormType() + "' ");
        }
        
        if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_ORACLE) {
        	sqlStat.append(" AND C.UPDATE_DATE = (" );
        	sqlStat.append(" SELECT MAX(B.UPDATE_DATE) ");
        	sqlStat.append(" FROM FORM_SUBMISSION B ");
        	sqlStat.append(" WHERE B.RECORD_STATUS = A.RECORD_STATUS ");
        	sqlStat.append(" AND B.FORM_RECORD_ID = A.ID ) ");
        	if (!Utility.isEmpty(actionForm.getFromDate())) {
            sqlStat.append(" AND C.UPDATE_DATE >= to_date('" + actionForm.getFromDate() + "', 'YYYY-MM-DD HH24:MI:SS') ");
          }
          if (!Utility.isEmpty(actionForm.getToDate())) {
            sqlStat.append(" AND C.UPDATE_DATE <= to_date('" + TextUtility.dbDateAdder(actionForm.getToDate(), 1) + "', 'YYYY-MM-DD HH24:MI:SS') ");
          }
        } else { 
        	/* Commented by Brook.Huang. There is none of differece between MSSQL and MYSQL.
          if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_MSSQL) {
          */
            sqlStat.append(" AND C.UPDATE_DATE = (" );
            sqlStat.append(" SELECT MAX(B.UPDATE_DATE) ");
            sqlStat.append(" FROM FORM_SUBMISSION B ");
            sqlStat.append(" WHERE B.RECORD_STATUS = A.RECORD_STATUS ");
            sqlStat.append(" AND B.FORM_RECORD_ID = A.ID ) ");
            /*
          }
          */
        	if (!Utility.isEmpty(actionForm.getFromDate())) {
            sqlStat.append(" AND C.UPDATE_DATE >= '" + actionForm.getFromDate() + "' ");
          }
          if (!Utility.isEmpty(actionForm.getToDate())) {
            sqlStat.append(" AND C.UPDATE_DATE <= '" +  TextUtility.dbDateAdder(actionForm.getToDate(), 1) + "' ");
          }
          if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_MYSQL) {
        	  sqlStat.append(" GROUP BY C.FORM_RECORD_ID ");
          }
        }
        //format the sql for any 'LIKE' statement contained
        sqlStat = this.getFormattedSQL(sqlStat.toString());

        // Form the ORDER clause for sorting.
        if (searchForm.isSortable()) {
          String sortAttribute = searchForm.getSortAttribute();
          if (sortAttribute.indexOf(".") < 0) {
            // handel order by Max(FORM_SUBMISSION.UPDATE_DATE).
            if ("UPDATE_DATE".equals(sortAttribute)) {
              sortAttribute = "C." + sortAttribute;
            }else if ("UPDATER_ID".equals(sortAttribute)){
              sortAttribute = "C." + sortAttribute;
            }else{
              sortAttribute = "A." + sortAttribute;  
            }
          }
          sqlStat.append("ORDER BY " + sortAttribute + " " + searchForm.getSortOrder());
        }

        // Get total number of record return.
        sqlStatCnt = this.getSelectCountSQL(sqlStat);
        preStatCnt = dbConn.prepareStatement(sqlStatCnt.toString());
        this.setPrepareStatement(preStatCnt, 1, GlobalConstant.RECORD_RELEASED);
        this.setPrepareStatement(preStatCnt, 2, GlobalConstant.RECORD_STATUS_ACTIVE);

/* Commented by Rollo for temporary solution of the bug. */
/* In the "Tracking", none of records can be shown after submitted a form */
//        this.setPrepareStatement(preStatCnt, 3, FormSubmission.FORM_SUBMISSION_STATU_PENDING);
        //this.setPrepareStatement(preStatCnt, 3, "");
/* End of comment */

        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          this.setPrepareStatement(preStatCnt, 3, searchKeyword);
        }

        rsCnt = preStatCnt.executeQuery();
        while (rsCnt.next()) {
          //totalNumOfRecord = rsCnt.getInt(1);
          totalNumOfRecord ++;
        }

        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }

        // Retrieve the result in row basis.
        sqlStat = this.getSelectListSQL(sqlStat, startOffset, pageSize);
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_RELEASED);
        this.setPrepareStatement(preStat, 2, GlobalConstant.RECORD_STATUS_ACTIVE);

/* Commented by Rollo for temporary solution of the bug. */
/* In the "Tracking", none of records can be shown after submitted a form */
//        this.setPrepareStatement(preStat, 3, FormSubmission.FORM_SUBMISSION_STATU_PENDING);
        //this.setPrepareStatement(preStat, 3, "");
/* End of comment */

        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          this.setPrepareStatement(preStat, 3, searchKeyword);
        }

        rs = preStat.executeQuery();

        this.positionCursor(rs, startOffset, pageSize);

        while (rs.next() && rowLoopCnt<pageSize) {
          FormSubmission tmpFormSubmission = new FormSubmission();

          tmpFormSubmission.setFormCode(getResultSetString(rs, "FORM_CODE"));
          tmpFormSubmission.setFormVersion(getResultSetString(rs, "FORM_VERSION"));
          tmpFormSubmission.setTitle(getResultSetString(rs, "TITLE"));
          tmpFormSubmission.setFormDocID(getResultSetInteger(rs, "FORM_DOC_ID"));
          tmpFormSubmission.setID(getResultSetInteger(rs, "ID"));
          tmpFormSubmission.setTrackID(getResultSetInteger(rs, "TRACK_ID"));
          tmpFormSubmission.setFormRecordID(getResultSetInteger(rs, "FORM_RECORD_ID"));
          tmpFormSubmission.setWorkflowRecordID(getResultSetInteger(rs, "WORKFLOW_RECORD_ID"));
          tmpFormSubmission.setIp(getResultSetString(rs, "IP"));
          tmpFormSubmission.setGuestName(getResultSetString(rs, "GUEST_NAME"));
          tmpFormSubmission.setEmail(getResultSetString(rs, "EMAIL"));
          tmpFormSubmission.setContactInfo(getResultSetString(rs, "CONTACT_INFO"));
          tmpFormSubmission.setDmsParentID(getResultSetInteger(rs, "DMS_PARENT_ID"));
          tmpFormSubmission.setStatus(getResultSetString(rs, "STATUS"));
          tmpFormSubmission.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormSubmission.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormSubmission.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormSubmission.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpFormSubmission.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpFormSubmission.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpFormSubmission.setCreatorName(UserInfoFactory.getUserFullName(tmpFormSubmission.getCreatorID()));
          tmpFormSubmission.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormSubmission.getUpdaterID()));
          tmpFormSubmission.setRecordCount(totalNumOfRecord);
          
          //get the bind workflow list
          //List workflowList = wfRecordDAO.getBindListByFormRecordIDFormGroupID(tmpFormSubmission.getFormRecordID(), ((ListFormSubmissionForm)searchForm).getFormGroupID());// falcon_delete
          List workflowList = wfRecordDAO.getBindListByFormRecordIDFormGroupID(tmpFormSubmission.getFormRecordID(), new Integer(getResultSetString(rs, "FORM_GROUP_ID")));// falcon_add
          if(!Utility.isEmpty(workflowList)){
            tmpFormSubmission.setWorkflowList(workflowList);
            tmpFormSubmission.setWorkflowListSize(workflowList.size());
          }
          
          tmpFormSubmission.setRowNum(startOffset++);
          ++rowLoopCnt;
          result.add(tmpFormSubmission);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }
      }
    }
  }


  /**
   * get the form submission list by the search section
   * @param searchForm
   * @return
   * @throws ApplicationException
   */
  public synchronized List getFormSubmissionListBySearchSection_TC(
      AbstractSearchForm searchForm,
      boolean isTracking )
      throws ApplicationException {
    String formRecordID = ((ListFormSubmissionForm)searchForm).getFormRecordID();
    PreparedStatement preStat = null;
    PreparedStatement preStat2 = null;
    PreparedStatement preStatCnt = null;
    ResultSet rs = null;
    ResultSet rs2 = null;
    ResultSet rsCnt = null;
    StringBuffer sqlStat = new StringBuffer();
    StringBuffer sqlStatTmp1 = new StringBuffer();
    StringBuffer sqlStatTmp2 = new StringBuffer();
    StringBuffer sqlStatCnt = new StringBuffer();
    List result = new ArrayList();
    int totalNumOfRecord = 0;
    int rowLoopCnt = 0;
    int startOffset = TextUtility.parseInteger(searchForm.getCurStartRowNo());
    int pageSize = TextUtility.parseInteger(searchForm.getPageOffset());

    ListFormSubmissionForm listFormSubmissionForm = (ListFormSubmissionForm)searchForm;
    WorkflowStepDAObject workflowStepDAO = new WorkflowStepDAObject(this.sessionContainer,this.dbConn);
    String fromDate = listFormSubmissionForm.getFromDate();
    String toDate = TextUtility.dbDateAdder(listFormSubmissionForm.getToDate(), 1);
    String attachedString = "";
    String attachedString2 = "";
    String basicSearchKeyword = listFormSubmissionForm.getBasicSearchKeyword();
    String searchSubmitter = listFormSubmissionForm.getSearchSubmitter();
    StringBuffer sqlStat2 = new StringBuffer();
    boolean isShowMyForm = !Utility.isEmpty(listFormSubmissionForm.getSearchFormType()) ? true : false;
    String workflowRecordID = listFormSubmissionForm.getWorkflowRecordID();
    String tmpStepIDStr = ""; 
    
    if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_ORACLE) {
    	if (!Utility.isEmpty(fromDate) && Utility.isEmpty(toDate)) {
        attachedString2 = " AND C.CREATE_DATE >= TO_DATE('" + fromDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      } else if (Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString2 = " AND C.CREATE_DATE <= TO_DATE('" + toDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      } else if (!Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString2 = " AND C.CREATE_DATE BETWEEN TO_DATE('" + fromDate + "', 'YYYY-MM-DD HH24:MI:SS') AND TO_DATE('"+  toDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      }
    } else {
    	if (!Utility.isEmpty(fromDate) && Utility.isEmpty(toDate)) {
        attachedString2 = " AND C.CREATE_DATE >= '" + fromDate + "' ";
      } else if (Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString2 = " AND C.CREATE_DATE <= '" + toDate + "' ";
      } else if (!Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString2 = " AND C.CREATE_DATE BETWEEN '" + fromDate + "' AND '"+  toDate + "' ";
      }
    }

    if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_ORACLE) {
      if (!Utility.isEmpty(fromDate) && Utility.isEmpty(toDate)) {
        attachedString = " AND WP.UPDATE_DATE >= TO_DATE('" + fromDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      } else if (Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND WP.UPDATE_DATE <= TO_DATE('" + toDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      } else if (!Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND WP.UPDATE_DATE BETWEEN TO_DATE('" + fromDate + "', 'YYYY-MM-DD HH24:MI:SS') AND TO_DATE('"+  toDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      }
    } else {
      if (!Utility.isEmpty(fromDate) && Utility.isEmpty(toDate)) {
        attachedString = " AND WP.UPDATE_DATE >= '" + fromDate + "' ";
      } else if (Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND WP.UPDATE_DATE <= '" + toDate + "' ";
      } else if (!Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND WP.UPDATE_DATE BETWEEN '" + fromDate + "' AND '"+  toDate + "' ";
      }
    }

    synchronized(dbConn) {
      try {
     	
      	if (isTracking || isShowMyForm) {
          sqlStatTmp1.append("SELECT DISTINCT C.FORM_RECORD_ID,  C.ID, C.WORKFLOW_RECORD_ID, C.TRACK_ID, WR.WORKFLOW_CODE, WR.WORKFLOW_VERSION, WS.ID STEP_ID, WS.STEP_NAME, WP.ID PROGRESS_ID, WP.STATUS STATUS, C.RECORD_STATUS, C.UPDATE_COUNT, MUR.CREATOR_ID CREATOR_ID, MUR.CREATE_DATE CREATE_DATE, MUR.UPDATER_ID UPDATER_ID,MUR.UPDATE_DATE UPDATE_DATE, C.STATUS SUBMISSION_STATUS ");  
        }else{
          sqlStatTmp1.append("SELECT DISTINCT C.FORM_RECORD_ID,  C.ID, C.WORKFLOW_RECORD_ID, C.TRACK_ID, WR.WORKFLOW_CODE, WR.WORKFLOW_VERSION, WS.ID STEP_ID, WS.STEP_NAME, WP.ID PROGRESS_ID, WP.STATUS STATUS, C.RECORD_STATUS, C.UPDATE_COUNT, WP.CREATOR_ID CREATOR_ID, C.CREATE_DATE CREATE_DATE, WP.UPDATER_ID UPDATER_ID,WP.UPDATE_DATE UPDATE_DATE, C.STATUS SUBMISSION_STATUS "); 
        }
      	sqlStatTmp1.append("FROM FORM_SUBMISSION C "); 
      	sqlStatTmp1.append("INNER JOIN WORKFLOW_RECORD WR ON WR.ID = C.WORKFLOW_RECORD_ID "); 
      	sqlStatTmp1.append("INNER JOIN WORKFLOW_STEP WS ON WR.ID = WS.WORKFLOW_RECORD_ID AND WS.STEP_SEQ <> "+WorkflowStep.END_STEP_SEQ_NO+" ");
      	sqlStatTmp1.append("INNER JOIN WORKFLOW_PROGRESS WP ON WP.WORKFLOW_STEP_ID = WS.ID  ");
      	if (isTracking || isShowMyForm){
          sqlStatTmp1.append("INNER JOIN MTM_WF_PROGRESS_USER_RECORD MUR ON MUR.WORKFLOW_PROGRESS_ID = WP.ID  ");
        }
        sqlStatTmp1.append("WHERE WS.RECORD_STATUS = WR.RECORD_STATUS AND WS.RECORD_STATUS = WP.RECORD_STATUS AND C.RECORD_STATUS = WS.RECORD_STATUS  ");
        sqlStatTmp1.append("AND C.TRACK_ID = WP.TRACK_ID ");
        sqlStatTmp1.append("AND C.RECORD_STATUS = ? AND C.FORM_RECORD_ID = ? ");
        if (isTracking || isShowMyForm) {
          sqlStatTmp1.append("AND MUR.UPDATER_ID = '"+ sessionContainer.getUserRecordID() +"' ");
          if (!Utility.isEmpty(workflowRecordID) && !"null".equals(workflowRecordID)){
            sqlStatTmp1.append("AND WR.ID = '"+ workflowRecordID +"' ");
          }
        }else{
          sqlStatTmp1.append("AND WP.STATUS <> '"+WorkflowProgress.STATUS_PENDING+"' AND C.STATUS <> '" + FormSubmission.FORM_SUBMISSION_STATU_SAVED + "' ");
          if (!Utility.isEmpty(searchSubmitter) && !"null".equals(searchSubmitter)){
            sqlStatTmp1.append("AND WP.UPDATER_ID = " + searchSubmitter + " ");
          }
        }
        
      	sqlStatTmp2.append("SELECT DISTINCT C.FORM_RECORD_ID, C.ID, C.WORKFLOW_RECORD_ID, C.TRACK_ID, WR.WORKFLOW_CODE, WR.WORKFLOW_VERSION, WS.ID STEP_ID, WS.STEP_NAME, WP.ID PROGRESS_ID, C.STATUS STATUS,C.RECORD_STATUS,C.UPDATE_COUNT, C.CREATOR_ID CREATOR_ID, C.CREATE_DATE CREATE_DATE, C.UPDATER_ID UPDATER_ID,C.UPDATE_DATE UPDATE_DATE, C.STATUS SUBMISSION_STATUS "); 
        sqlStatTmp2.append("FROM FORM_SUBMISSION C "); 
        sqlStatTmp2.append("LEFT JOIN WORKFLOW_RECORD WR ON WR.ID = C.WORKFLOW_RECORD_ID "); 
        sqlStatTmp2.append("LEFT JOIN WORKFLOW_STEP WS ON WR.ID = WS.WORKFLOW_RECORD_ID ");
        sqlStatTmp2.append("LEFT JOIN WORKFLOW_PROGRESS WP ON WP.WORKFLOW_STEP_ID = WS.ID AND WS.RECORD_STATUS = WR.RECORD_STATUS AND WS.RECORD_STATUS = WP.RECORD_STATUS ");
        sqlStatTmp2.append("WHERE C.RECORD_STATUS = ? AND C.FORM_RECORD_ID = ? AND C.WORKFLOW_RECORD_ID IS NULL ");
        
        if (isTracking || isShowMyForm) {
          sqlStatTmp2.append("AND C.CREATOR_ID = '"+ sessionContainer.getUserRecordID() +"' ");
        }else{
          sqlStatTmp2.append("AND  C.STATUS <> '" + FormSubmission.FORM_SUBMISSION_STATU_SAVED + "' ");
          if (!Utility.isEmpty(searchSubmitter) && !"null".equals(searchSubmitter)){
            sqlStatTmp2.append("AND C.CREATOR_ID = " + searchSubmitter + " ");
          }
        }

        if ((isTracking || isShowMyForm) && !Utility.isEmpty(workflowRecordID) && !"null".equals(workflowRecordID)){                            
          List stepList = workflowStepDAO.getStepListByWorkflowRecordIDFormRecordIDUserRecordID(new Integer(workflowRecordID),new Integer(formRecordID),sessionContainer.getUserRecordID());
          for (int n=0; n<stepList.size(); n++){
            WorkflowStep workflowStep = (WorkflowStep)stepList.get(n);
            tmpStepIDStr += ((tmpStepIDStr.length()>0)?",":"") + workflowStep.getID();
          }        
        }
        
        if(!Utility.isEmpty(basicSearchKeyword)){
          // For Text Box
          sqlStat2.append("SELECT DISTINCT E.SUBMISSION_ID FROM FORM_DATA_ELEMENT E ");
          sqlStat2.append("INNER JOIN FORM_DATA D ON D.DATA_ELEMENT_ID = E.ID ");
          sqlStat2.append("LEFT JOIN WORKFLOW_PROGRESS WP ON E.WORKFLOW_PROGRESS_ID = WP.ID ");
          sqlStat2.append("WHERE D.DATA_STRING " + searchForm.getBasicSearchType() + " ? ");
          if(searchForm.isSearchable()){
            sqlStat2.append("AND E.ELEMENT_ID = ? ");
          }
          if (!Utility.isEmpty(workflowRecordID) && !"null".equals(workflowRecordID)){            
            tmpStepIDStr = !Utility.isEmpty(tmpStepIDStr) ? tmpStepIDStr : "-1";
            sqlStat2.append("AND WP.WORKFLOW_STEP_ID IN ("+tmpStepIDStr+") ");            
          }
          preStat2 = dbConn.prepareStatement(sqlStat2.toString());
          this.setPrepareStatement(preStat2, 1, this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType()));  
          if(searchForm.isSearchable()){  
            this.setPrepareStatement(preStat2, 2, searchForm.getBasicSearchField());
          }
            
        	rs2= preStat2.executeQuery();
        	String submissionID = "";
          while (rs2.next()) {
            submissionID += ((submissionID.length()>0)?",":"") + getResultSetInteger(rs2, "SUBMISSION_ID");
          }
          // For Select Box, Radio Button, Check Box
          sqlStat2 = new StringBuffer();
          sqlStat2.append("SELECT DISTINCT E.SUBMISSION_ID ");
          sqlStat2.append("FROM FORM_DATA_ELEMENT E INNER JOIN FORM_DATA D ON D.DATA_ELEMENT_ID = E.ID ");
          sqlStat2.append("INNER JOIN FORM_SELECTION_FIELD F ON E.ELEMENT_ID = F.ELEMENT_ID ");
          sqlStat2.append("INNER JOIN FORM_SELECTION_FIELD_OPTION G ON G.SELECTION_FIELD_ID = F.ID ");
          sqlStat2.append("LEFT JOIN WORKFLOW_PROGRESS WP ON E.WORKFLOW_PROGRESS_ID = WP.ID ");
          sqlStat2.append("WHERE D.DATA_STRING = G.START_VALUE ");
          sqlStat2.append("AND G.LABEL " + searchForm.getBasicSearchType() + " ? ");
          if(searchForm.isSearchable()){
            sqlStat2.append("AND E.ELEMENT_ID = ? ");
          }
          if (!Utility.isEmpty(workflowRecordID) && !"null".equals(workflowRecordID)){
            tmpStepIDStr = !Utility.isEmpty(tmpStepIDStr) ? tmpStepIDStr : "-1";
            sqlStat2.append("AND WP.WORKFLOW_STEP_ID IN ("+tmpStepIDStr+") ");            
          }
          preStat2 = dbConn.prepareStatement(sqlStat2.toString());
          this.setPrepareStatement(preStat2, 1, this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType()));  
          if(searchForm.isSearchable()){  
            this.setPrepareStatement(preStat2, 2, searchForm.getBasicSearchField());
          }
          rs2= preStat2.executeQuery();
          while (rs2.next()) {
            submissionID += ((submissionID.length()>0)?",":"") + getResultSetInteger(rs2, "SUBMISSION_ID");
          }

          if (!Utility.isEmpty(submissionID)) {
            sqlStatTmp1.append("           AND C.ID IN ("+submissionID+") ");
            sqlStatTmp2.append("           AND C.ID IN ("+submissionID+") ");
          }else{
          	throw new ApplicationException(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR);
          }
          //}
          try { rs2.close(); } catch (Exception ignore) {} finally { rs2 = null; }
          try { preStat2.close(); } catch (Exception ignore) {} finally { preStat2 = null; }
        }

        sqlStatTmp1.append(attachedString);
        sqlStatTmp2.append(attachedString2);
        sqlStat.append(sqlStatTmp1);
        sqlStat.append("UNION ");
        sqlStat.append(sqlStatTmp2);
        sqlStat = this.getFormattedSQL(sqlStat.toString());

        // Form the ORDER clause for sorting.
        if (searchForm.isSortable()) {
          String sortAttribute = searchForm.getSortAttribute();
          if (sortAttribute.indexOf(".") < 0) {
            if ("TITLE".equals(sortAttribute)){
              sortAttribute = "UPDATE_DATE";
              searchForm.setSortAttribute("UPDATE_DATE");
              searchForm.setSortOrder("DESC");
            }
          }
          sqlStat.append("ORDER BY " + sortAttribute + " " + searchForm.getSortOrder());
        }
  
        // Get total number of record return.
        sqlStatCnt = this.getSelectCountSQL(sqlStatTmp1);      
        preStatCnt = dbConn.prepareStatement(sqlStatCnt.toString());
        this.setPrepareStatement(preStatCnt, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStatCnt, 2, formRecordID);
        rsCnt = preStatCnt.executeQuery();
        if (rsCnt.next()) {
          totalNumOfRecord = rsCnt.getInt(1);
        }
        sqlStatCnt = new StringBuffer("SELECT COUNT(DISTINCT C.ID) FROM ");
        int idx = sqlStatTmp2.indexOf("FROM ");
        sqlStatCnt.append(sqlStatTmp2.substring(idx + 5));
        if (sqlStatCnt.indexOf("ORDER BY") >= 0) {
          sqlStatCnt = new StringBuffer(sqlStatCnt.substring(0, sqlStatCnt.indexOf("ORDER BY") - 1));
        }        
        preStatCnt = dbConn.prepareStatement(sqlStatCnt.toString());
        this.setPrepareStatement(preStatCnt, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStatCnt, 2, formRecordID);
        rsCnt = preStatCnt.executeQuery();
        if (rsCnt.next()) {
          totalNumOfRecord += rsCnt.getInt(1);
        }
        
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }

        // Retrieve the result in row basis.
        if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_MSSQL){
          sqlStat = this.getSelectListMSSQLForForm(sqlStat, startOffset, pageSize);
        }else{
          sqlStat = this.getSelectListSQL(sqlStat, startOffset, pageSize);	
        }
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 2, formRecordID);
        this.setPrepareStatement(preStat, 3, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 4, formRecordID);
        
        rs = preStat.executeQuery();

        this.positionCursor(rs, startOffset, pageSize);

        while (rs.next() && rowLoopCnt<pageSize) {
          FormSubmission tmpFormSubmission = new FormSubmission();

          tmpFormSubmission.setID(getResultSetInteger(rs, "ID"));
          tmpFormSubmission.setTrackID(getResultSetInteger(rs, "TRACK_ID"));
          tmpFormSubmission.setFormRecordID(getResultSetInteger(rs, "FORM_RECORD_ID"));
          tmpFormSubmission.setWorkflowRecordID(getResultSetInteger(rs, "WORKFLOW_RECORD_ID"));
          tmpFormSubmission.setWorkflowCode(getResultSetString(rs, "WORKFLOW_CODE"));
          tmpFormSubmission.setWorkflowStepID(getResultSetInteger(rs, "STEP_ID"));
          tmpFormSubmission.setWorkflowStepName(getResultSetString(rs, "STEP_NAME"));    
          tmpFormSubmission.setProgressID(getResultSetInteger(rs, "PROGRESS_ID"));
          tmpFormSubmission.setStatus(getResultSetString(rs, "STATUS"));
          tmpFormSubmission.setSubmissionStatus(getResultSetString(rs, "SUBMISSION_STATUS"));
          tmpFormSubmission.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormSubmission.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormSubmission.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormSubmission.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpFormSubmission.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpFormSubmission.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpFormSubmission.setCreatorName(UserInfoFactory.getUserFullName(tmpFormSubmission.getCreatorID()));
          tmpFormSubmission.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormSubmission.getUpdaterID()));
          tmpFormSubmission.setRecordCount(totalNumOfRecord);

          // Retrive the workflow relationship.
//          if (isTracking) {
            com.dcivision.workflow.dao.MtmWorkflowProgressSystemObjectDAObject mtmWfProgressSysObjDAO = new com.dcivision.workflow.dao.
              MtmWorkflowProgressSystemObjectDAObject(sessionContainer, dbConn);
            com.dcivision.workflow.dao.WorkflowRecordDAObject workflowRecordDAO = new com.dcivision.workflow.dao.WorkflowRecordDAObject(sessionContainer, dbConn);

            List tmpList = mtmWfProgressSysObjDAO.getListByBeanClassNameObjectID(tmpFormSubmission.getClass().getName(), getResultSetInteger(rs, "ID"));
            List workflowRelationshipList = new ArrayList();

            if(tmpList.size()>0){
              com.dcivision.workflow.bean.MtmWorkflowProgressSystemObject tmpObj = (com.dcivision.workflow.bean.MtmWorkflowProgressSystemObject)tmpList.get(0);
              com.dcivision.workflow.bean.WorkflowRecord wfRec = (com.dcivision.workflow.bean.WorkflowRecord)workflowRecordDAO.getObjectByTrackID(tmpObj.getTrackID());
              if (wfRec != null) {
                workflowRelationshipList.add(new Object[] {wfRec, tmpObj.getTrackID()});
              }
              tmpFormSubmission.setWorkflowRelationshipList(workflowRelationshipList);
            }
            mtmWfProgressSysObjDAO=null;
            workflowRecordDAO=null;
//          }

          tmpFormSubmission.setRowNum(startOffset++);
          ++rowLoopCnt;
          result.add(tmpFormSubmission);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }
      }
    }
  }

  
  public synchronized List getFormSubmissionListBySearchSection(
      AbstractSearchForm searchForm,
      boolean isTracking )
      throws ApplicationException {
    AbstractQuery query = QueryUtil.createQuery();
    PreparedStatement preStat = null;
   
    PreparedStatement preStatCnt = null;
    PreparedStatement preStatCnt2 = null;
    ResultSet rs = null;
 
    ResultSet rsCnt = null;
    ResultSet rsCnt2 = null;
    StringBuffer sqlStat = null;
    StringBuffer sqlbindWFCnt =null;
    StringBuffer sqlnotbindWFCnt= null;
   
    List result = new ArrayList();
    int totalNumOfRecord = 0;
    int rowLoopCnt = 0;
    int startOffset = TextUtility.parseInteger(searchForm.getCurStartRowNo());
    int pageSize = TextUtility.parseInteger(searchForm.getPageOffset());

    AbstractQuery bindWithWorkflowFormSubmissionListCrossStepQuery = null;
    AbstractQuery notBindWithWorkflowFormSubmissionListQuery = null;
    
    synchronized(dbConn) {
      try {
        bindWithWorkflowFormSubmissionListCrossStepQuery = this.getFormSubmissionListWithWorkflowStep(searchForm, isTracking);
        notBindWithWorkflowFormSubmissionListQuery = this.getNotBindWorkflowFormSubmissionSearchListSQL(searchForm, isTracking, true);
        
        query.subQuery(bindWithWorkflowFormSubmissionListCrossStepQuery);
        query.append("\nUNION\n");
        query.subQuery(notBindWithWorkflowFormSubmissionListQuery);
        query.pack();
        
        sqlStat = new StringBuffer(query.toString());
        sqlStat = this.getFormattedSQL(sqlStat.toString());
        
        // Form the ORDER clause for sorting.
        if (searchForm.isSortable()) {
          String sortAttribute = searchForm.getSortAttribute();
          if (sortAttribute.indexOf(".") < 0) {
            if ("TITLE".equals(sortAttribute)){
              sortAttribute = "UPDATE_DATE";
              searchForm.setSortAttribute("UPDATE_DATE");
              searchForm.setSortOrder("DESC");
            }

          }
          //sqlStat.append("ORDER BY " + sortAttribute + " " + searchForm.getSortOrder());
          sqlStat = this.getUnionOrderSQL(sqlStat, sortAttribute, searchForm.getSortOrder());
        }

        sqlbindWFCnt = this.getSelectCountSQL(new StringBuffer(bindWithWorkflowFormSubmissionListCrossStepQuery.toString()));
        preStatCnt = dbConn.prepareStatement(sqlbindWFCnt.toString());
        this.setPreparedStatement(preStatCnt, 1, bindWithWorkflowFormSubmissionListCrossStepQuery.getAllParameters());
        rsCnt = preStatCnt.executeQuery();
        if (rsCnt.next()) {
          totalNumOfRecord = rsCnt.getInt(1);
        }        
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }
        
        sqlnotbindWFCnt = this.getSelectCountSQL(new StringBuffer(notBindWithWorkflowFormSubmissionListQuery.toString()));
        preStatCnt2 = dbConn.prepareStatement(sqlnotbindWFCnt.toString());
        this.setPreparedStatement(preStatCnt2, 1, notBindWithWorkflowFormSubmissionListQuery.getAllParameters());
        rsCnt2 = preStatCnt2.executeQuery();
        if (rsCnt2.next()) {
          totalNumOfRecord += rsCnt2.getInt(1);
        } 
        try { rsCnt2.close(); } catch (Exception ignore) {} finally { rsCnt2 = null; }
        try { preStatCnt2.close(); } catch (Exception ignore) {} finally { preStatCnt2 = null; }
        
        // Retrieve the result in row basis.
        sqlStat = this.getSelectListSQL(sqlStat, startOffset, pageSize);
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPreparedStatement(preStat, 1, query.getAllParameters());        
        
        rs = preStat.executeQuery();

        this.positionCursor(rs, startOffset, pageSize);
        
        while (rs.next() && rowLoopCnt<pageSize) {
          FormSubmission tmpFormSubmission = new FormSubmission();

          tmpFormSubmission.setID(getResultSetInteger(rs, "ID"));
          tmpFormSubmission.setTrackID(getResultSetInteger(rs, "TRACK_ID"));
          tmpFormSubmission.setFormRecordID(getResultSetInteger(rs, "FORM_RECORD_ID"));
          tmpFormSubmission.setWorkflowRecordID(getResultSetInteger(rs, "WORKFLOW_RECORD_ID"));
          tmpFormSubmission.setWorkflowCode(getResultSetString(rs, "WORKFLOW_CODE"));
          tmpFormSubmission.setWorkflowStepID(getResultSetInteger(rs, "STEP_ID"));
          tmpFormSubmission.setWorkflowStepName(getResultSetString(rs, "STEP_NAME"));    
          tmpFormSubmission.setProgressID(getResultSetInteger(rs, "PROGRESS_ID"));
          tmpFormSubmission.setStatus(getResultSetString(rs, "STATUS"));
          tmpFormSubmission.setSubmissionStatus(getResultSetString(rs, "SUBMISSION_STATUS"));
          tmpFormSubmission.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormSubmission.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormSubmission.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormSubmission.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpFormSubmission.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpFormSubmission.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpFormSubmission.setCreatorName(UserInfoFactory.getUserFullName(tmpFormSubmission.getCreatorID()));
          tmpFormSubmission.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormSubmission.getUpdaterID()));
          tmpFormSubmission.setRecordCount(totalNumOfRecord);

          // Retrive the workflow relationship.
//          if (isTracking) {
            com.dcivision.workflow.dao.MtmWorkflowProgressSystemObjectDAObject mtmWfProgressSysObjDAO = new com.dcivision.workflow.dao.
              MtmWorkflowProgressSystemObjectDAObject(sessionContainer, dbConn);
            com.dcivision.workflow.dao.WorkflowRecordDAObject workflowRecordDAO = new com.dcivision.workflow.dao.WorkflowRecordDAObject(sessionContainer, dbConn);

            List tmpList = mtmWfProgressSysObjDAO.getListByBeanClassNameObjectID(tmpFormSubmission.getClass().getName(), getResultSetInteger(rs, "ID"));
            List workflowRelationshipList = new ArrayList();

            if(tmpList.size()>0){
              com.dcivision.workflow.bean.MtmWorkflowProgressSystemObject tmpObj = (com.dcivision.workflow.bean.MtmWorkflowProgressSystemObject)tmpList.get(0);
              com.dcivision.workflow.bean.WorkflowRecord wfRec = (com.dcivision.workflow.bean.WorkflowRecord)workflowRecordDAO.getObjectByTrackID(tmpObj.getTrackID());
              if (wfRec != null) {
                workflowRelationshipList.add(new Object[] {wfRec, tmpObj.getTrackID()});
              }
              tmpFormSubmission.setWorkflowRelationshipList(workflowRelationshipList);
            }
            mtmWfProgressSysObjDAO=null;
            workflowRecordDAO=null;
//          }

          tmpFormSubmission.setRowNum(startOffset++);
          ++rowLoopCnt;
          result.add(tmpFormSubmission);
        }
        return(result);
        
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }
      }
    }
    
  }
  
  /**
   * getFormSubmissionListWithWorkflowStep
   * get the subQuery of the formsubmission list which cross the workflow step band with 
   * @param searchForm
   * @param isTracking
   * @return
   */
  private AbstractQuery getFormSubmissionListWithWorkflowStep(AbstractSearchForm searchForm,boolean isTracking){
    
    AbstractQuery subQuery = new SubQuery();
   
    StringBuffer sqlStatTmp1 = new StringBuffer();
    String formRecordID = ((ListFormSubmissionForm)searchForm).getFormRecordID();
    
    ListFormSubmissionForm listFormSubmissionForm = (ListFormSubmissionForm)searchForm;
    WorkflowStepDAObject workflowStepDAO = new WorkflowStepDAObject(this.sessionContainer,this.dbConn);
    String fromDate = listFormSubmissionForm.getFromDate();
    String toDate = TextUtility.dbDateAdder(listFormSubmissionForm.getToDate(), 1);
    String attachedString = "";
    String basicSearchKeyword = listFormSubmissionForm.getBasicSearchKeyword();
    String searchSubmitter = listFormSubmissionForm.getSearchSubmitter();
    boolean isShowMyForm = !Utility.isEmpty(listFormSubmissionForm.getSearchFormType()) ? true : false;
    String workflowRecordID = listFormSubmissionForm.getWorkflowRecordID();

    if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_ORACLE) {
      if (!Utility.isEmpty(fromDate) && Utility.isEmpty(toDate)) {
        attachedString = " AND WP.UPDATE_DATE >= TO_DATE('" + fromDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      } else if (Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND WP.UPDATE_DATE <= TO_DATE('" + toDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      } else if (!Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND WP.UPDATE_DATE BETWEEN TO_DATE('" + fromDate + "', 'YYYY-MM-DD HH24:MI:SS') AND TO_DATE('"+  toDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      }
    } else {
      if (!Utility.isEmpty(fromDate) && Utility.isEmpty(toDate)) {
        attachedString = " AND WP.UPDATE_DATE >= '" + fromDate + "' ";
      } else if (Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND WP.UPDATE_DATE <= '" + toDate + "' ";
      } else if (!Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND WP.UPDATE_DATE BETWEEN '" + fromDate + "' AND '"+  toDate + "' ";
      }
    }
    
    if (isTracking || isShowMyForm) {
      sqlStatTmp1.append("SELECT DISTINCT C.FORM_RECORD_ID,  C.ID,  WR.ID WORKFLOW_RECORD_ID, SO.TRACK_ID TRACK_ID, WR.WORKFLOW_CODE, WR.WORKFLOW_VERSION, WS.ID STEP_ID, WS.STEP_NAME STEP_NAME, WP.STATUS STATUS, C.RECORD_STATUS, C.UPDATE_COUNT, MUR.CREATOR_ID CREATOR_ID, C.CREATE_DATE CREATE_DATE, MUR.UPDATER_ID UPDATER_ID,MUR.UPDATE_DATE UPDATE_DATE, WP.ID PROGRESS_ID, WS.STEP_SEQ, C.STATUS SUBMISSION_STATUS ");
    }else{
      sqlStatTmp1.append("SELECT DISTINCT C.FORM_RECORD_ID,  C.ID,  WR.ID WORKFLOW_RECORD_ID, SO.TRACK_ID TRACK_ID, WR.WORKFLOW_CODE, WR.WORKFLOW_VERSION, WS.ID STEP_ID, WS.STEP_NAME STEP_NAME, WP.STATUS STATUS, C.RECORD_STATUS, C.UPDATE_COUNT, WP.CREATOR_ID CREATOR_ID, C.CREATE_DATE CREATE_DATE, WP.UPDATER_ID UPDATER_ID,WP.UPDATE_DATE UPDATE_DATE, WP.ID PROGRESS_ID, WS.STEP_SEQ, C.STATUS SUBMISSION_STATUS  ");
    }
    sqlStatTmp1.append("FROM FORM_SUBMISSION C ");
    if(!Utility.isEmpty(basicSearchKeyword)){
      sqlStatTmp1.append("INNER JOIN FORM_DATA_ELEMENT FE ON C.ID=FE.SUBMISSION_ID \n");
      sqlStatTmp1.append("INNER JOIN FORM_DATA FD ON FE.ID=FD.DATA_ELEMENT_ID\n");
      sqlStatTmp1.append("LEFT JOIN FORM_SELECTION_FIELD FS ON FE.ELEMENT_ID=FS.ELEMENT_ID \n");
      sqlStatTmp1.append("LEFT JOIN FORM_SELECTION_FIELD_OPTION FO ON FS.ID=FO.SELECTION_FIELD_ID \n");
    }
    sqlStatTmp1.append("INNER JOIN MTM_WF_RECORD_OBJECT_LINK OL ON C.FORM_RECORD_ID = OL.OBJECT_ID AND OL.WORKFLOW_CATEGORY_ID = '" +SystemWorkflowConstant.FMB_SUBMISSION_BY_FORM+ "' \n");       // falcon_delete
    sqlStatTmp1.append("INNER JOIN WORKFLOW_RECORD WR ON WR.ID = OL.WORKFLOW_RECORD_ID \n");
    sqlStatTmp1.append("INNER JOIN WORKFLOW_STEP WS ON WR.ID = WS.WORKFLOW_RECORD_ID AND WS.STEP_SEQ <> '" +WorkflowStep.END_STEP_SEQ_NO+ "' AND WS.ACTION_TYPE <> '" +WorkflowStep.ACTION_TYPE_SYSTEM_AUTO+ "' AND WS.ACTION_TYPE <> '" + WorkflowStep.ACTION_TYPE_FORM_DRIVEN+ "' \n");
    sqlStatTmp1.append("INNER JOIN WORKFLOW_PROGRESS WP ON WP.WORKFLOW_STEP_ID = WS.ID \n");
    sqlStatTmp1.append("INNER JOIN MTM_WF_PROGRESS_SYSTEM_OBJECT SO ON C.ID = SO.OBJECT_ID AND SO.BEAN_CLASS_NAME  ='com.dcivision.form.bean.FormSubmission' \n");
    if (isTracking || isShowMyForm) {
      sqlStatTmp1.append("INNER JOIN MTM_WF_PROGRESS_USER_RECORD MUR ON MUR.WORKFLOW_PROGRESS_ID = WP.ID \n");
    }
    sqlStatTmp1.append("WHERE WS.RECORD_STATUS = WR.RECORD_STATUS AND WS.RECORD_STATUS = WR.RECORD_STATUS AND C.RECORD_STATUS = WS.RECORD_STATUS \n");
    sqlStatTmp1.append("AND WP.TRACK_ID = SO.TRACK_ID ");
    sqlStatTmp1.append("AND C.RECORD_STATUS = ? AND C.FORM_RECORD_ID = ? ");
    if (isTracking || isShowMyForm) {
      sqlStatTmp1.append("AND MUR.UPDATER_ID = '"+ sessionContainer.getUserRecordID() +"' ");
      if (!Utility.isEmpty(workflowRecordID) && !"null".equals(workflowRecordID)){
        sqlStatTmp1.append("AND WR.ID = '"+ workflowRecordID +"' ");
      }
    }else{
      sqlStatTmp1.append("AND WP.STATUS <> 'P' AND C.STATUS <> '" + FormSubmission.FORM_SUBMISSION_STATU_SAVED + "' ");
      if (!Utility.isEmpty(searchSubmitter) && !"null".equals(searchSubmitter)){
        sqlStatTmp1.append("AND WP.UPDATER_ID = " + searchSubmitter + " ");
      }
    }
    // Keyword search
    if(!Utility.isEmpty(basicSearchKeyword)){
      String searchField = searchForm.getBasicSearchField();
      sqlStatTmp1.append("  AND ( (FS.ID IS NULL AND FD.RECORD_STATUS=? AND FD.DATA_STRING " + searchForm.getBasicSearchType() + " ?) \n");
      sqlStatTmp1.append("            OR (FS.ID IS NOT NULL AND FD.RECORD_STATUS=? AND FD.DATA_STRING=FO.START_VALUE AND FO.LABEL " + searchForm.getBasicSearchType() + " ?) \n");
      sqlStatTmp1.append("            )\n");
      if(!Utility.isEmpty(basicSearchKeyword) && !Utility.isEmpty(searchField)){
        sqlStatTmp1.append("  AND FE.ELEMENT_ID=?\n");
      }
    }
    
    subQuery.append(sqlStatTmp1.toString());
    subQuery.append(attachedString.toLowerCase());
    if((isTracking || isShowMyForm)&&!Utility.isEmpty(workflowRecordID)&&!workflowRecordID.equalsIgnoreCase("null")){
      subQuery.append(" AND WORKFLOW_STEP_ID IN (").subQuery(workflowStepDAO.getStepListSQLByWorkflowRecordIDFormRecordIDUserRecordID(new Integer(workflowRecordID),new Integer(formRecordID),sessionContainer.getUserRecordID())).append(") ");
    }
    int i=1;
    //this.setPrepareStatement(preStatCnt, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
    //this.setPrepareStatement(preStatCnt, 2, formRecordID);
    subQuery.setParameter(i++, GlobalConstant.RECORD_STATUS_ACTIVE);
    subQuery.setParameter(i++, formRecordID);
    if(!Utility.isEmpty(basicSearchKeyword)){
      String searchField = listFormSubmissionForm.getBasicSearchField();
      String searchKeyword = this.getFormattedKeyword(listFormSubmissionForm.getBasicSearchKeyword(), listFormSubmissionForm.getBasicSearchType());
     
      subQuery.setParameter(i++, GlobalConstant.RECORD_STATUS_ACTIVE);
      
      subQuery.setParameter(i++, searchKeyword);
     
      subQuery.setParameter(i++, GlobalConstant.RECORD_STATUS_ACTIVE);
      
      subQuery.setParameter(i++, searchKeyword);
      if(!Utility.isEmpty(basicSearchKeyword) && !Utility.isEmpty(searchField)){
       
        subQuery.setParameter(i++, searchField);
      }
    }
   
    subQuery.pack();
    return subQuery;
  }
  
  
  /**
   * get the form submission list by the search section
   * @param searchForm
   * @return
   * @throws ApplicationException
   */
  public synchronized List getFormSubmissionWholeFormListBySearchSection_TC(
      AbstractSearchForm searchForm,
      boolean isTracking )
      throws ApplicationException {
    String formRecordID = ((ListFormSubmissionForm)searchForm).getFormRecordID();
    PreparedStatement preStat = null;
    PreparedStatement preStat2 = null;
    PreparedStatement preStatCnt = null;
    ResultSet rs = null;
    ResultSet rs2 = null;
    ResultSet rsCnt = null;
    StringBuffer sqlStat = new StringBuffer();
    StringBuffer sqlStatTmp1 = new StringBuffer();
    StringBuffer sqlStatCnt = new StringBuffer();
    List result = new ArrayList();
    int totalNumOfRecord = 0;
    int rowLoopCnt = 0;
    int startOffset = TextUtility.parseInteger(searchForm.getCurStartRowNo());
    int pageSize = TextUtility.parseInteger(searchForm.getPageOffset());

    ListFormSubmissionForm listFormSubmissionForm = (ListFormSubmissionForm)searchForm;
    String fromDate = listFormSubmissionForm.getFromDate();
    String toDate = TextUtility.dbDateAdder(listFormSubmissionForm.getToDate(), 1);
    String attachedString = "";
    String attachedString2 = "";
    String basicSearchKeyword = listFormSubmissionForm.getBasicSearchKeyword();
    String searchSubmitter = listFormSubmissionForm.getSearchSubmitter();
    StringBuffer sqlStat2 = new StringBuffer();
    boolean isShowMyForm = !Utility.isEmpty(listFormSubmissionForm.getSearchFormType()) ? true : false;
    String workflowRecordID = listFormSubmissionForm.getWorkflowRecordID();
    String trackingSubmissionID = "";


    if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_ORACLE) {
      if (!Utility.isEmpty(fromDate) && Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE >= TO_DATE('" + fromDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      } else if (Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE <= TO_DATE('" + toDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      } else if (!Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE BETWEEN TO_DATE('" + fromDate + "', 'YYYY-MM-DD HH24:MI:SS') AND TO_DATE('"+  toDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      }
    } else {
      if (!Utility.isEmpty(fromDate) && Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE >= '" + fromDate + "' ";
      } else if (Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE <= '" + toDate + "' ";
      } else if (!Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE BETWEEN '" + fromDate + "' AND '"+  toDate + "' ";
      }
    }

    synchronized(dbConn) {
      try {
        
        if (isTracking || isShowMyForm) {
          sqlStatTmp1.append("SELECT DISTINCT C.FORM_RECORD_ID,  C.ID ");             
          sqlStatTmp1.append("FROM FORM_SUBMISSION C "); 
          sqlStatTmp1.append("INNER JOIN MTM_WF_RECORD_OBJECT_LINK OL ON C.FORM_RECORD_ID = OL.OBJECT_ID AND OL.WORKFLOW_CATEGORY_ID = '10' "); 
          sqlStatTmp1.append("INNER JOIN WORKFLOW_RECORD WR ON WR.ID = OL.WORKFLOW_RECORD_ID ");
          sqlStatTmp1.append("INNER JOIN WORKFLOW_STEP WS ON WR.ID = WS.WORKFLOW_RECORD_ID AND WS.STEP_SEQ <> '999999999' ");
          sqlStatTmp1.append("INNER JOIN WORKFLOW_PROGRESS WP ON WP.WORKFLOW_STEP_ID = WS.ID ");
          sqlStatTmp1.append("INNER JOIN MTM_WF_PROGRESS_SYSTEM_OBJECT SO ON C.ID = SO.OBJECT_ID AND SO.BEAN_CLASS_NAME  ='com.dcivision.form.bean.FormSubmission' ");            
          sqlStatTmp1.append("INNER JOIN MTM_WF_PROGRESS_USER_RECORD MUR ON MUR.WORKFLOW_PROGRESS_ID = WP.ID ");            
          sqlStatTmp1.append("WHERE WS.RECORD_STATUS = WR.RECORD_STATUS AND WS.RECORD_STATUS = WR.RECORD_STATUS AND C.RECORD_STATUS = WS.RECORD_STATUS  ");
          sqlStatTmp1.append("AND WP.TRACK_ID = SO.TRACK_ID ");
          sqlStatTmp1.append("AND C.RECORD_STATUS = ? AND C.FORM_RECORD_ID = ? ");              
          sqlStatTmp1.append("AND MUR.UPDATER_ID = '"+ sessionContainer.getUserRecordID() +"' ");
          if (!Utility.isEmpty(workflowRecordID) && !"null".equals(workflowRecordID)){
            sqlStatTmp1.append("AND WR.ID = '"+ workflowRecordID +"' ");
          }
          sqlStatTmp1 = this.getSelectListSQL(sqlStatTmp1, startOffset, pageSize);
          preStat = dbConn.prepareStatement(sqlStatTmp1.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
          this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
          this.setPrepareStatement(preStat, 2, formRecordID);
          rs= preStat.executeQuery();
          while (rs.next()) {
            trackingSubmissionID += ((trackingSubmissionID.length()>0)?",":"") + getResultSetInteger(rs, "ID");
          }
          
        }
        
        sqlStat.append("SELECT C.ID, C.TRACK_ID, C.FORM_RECORD_ID, C.WORKFLOW_RECORD_ID, WR.WORKFLOW_CODE, C.IP,C.GUEST_NAME,C.EMAIL,C.CONTACT_INFO, C.DMS_PARENT_ID, C.STATUS,C.RECORD_STATUS,C.UPDATE_COUNT, C.CREATOR_ID, C.CREATE_DATE, C.UPDATER_ID,C.UPDATE_DATE ");
        sqlStat.append("FROM FORM_SUBMISSION C ");
        sqlStat.append("LEFT JOIN WORKFLOW_RECORD WR ON WR.ID = C.WORKFLOW_RECORD_ID ");
        sqlStat.append("WHERE C.RECORD_STATUS = ? AND C.FORM_RECORD_ID = ? ");
        if (isTracking || isShowMyForm) { 
          if (!Utility.isEmpty(workflowRecordID) && !"null".equals(workflowRecordID)){
            sqlStat.append("AND WR.ID = '"+ workflowRecordID +"' ");
          }
          sqlStat.append("AND ( C.CREATOR_ID = '"+ sessionContainer.getUserRecordID() +"' ");
          if (!Utility.isEmpty(trackingSubmissionID)){
            sqlStat.append("OR C.ID IN (" + trackingSubmissionID +")  ");  
          }
          sqlStat.append(" ) ");            
        }else{
          sqlStat.append("AND C.STATUS <> '" + FormSubmission.FORM_SUBMISSION_STATU_SAVED + "' ");
          if (!Utility.isEmpty(searchSubmitter) && !"null".equals(searchSubmitter)){
            sqlStat.append("AND C.CREATOR_ID = " + searchSubmitter + " ");
          }
        }
        
        if(!Utility.isEmpty(basicSearchKeyword)){
          // For Text Box
          sqlStat2.append("SELECT DISTINCT E.SUBMISSION_ID FROM FORM_DATA_ELEMENT E, FORM_DATA D ");
          sqlStat2.append("WHERE D.DATA_ELEMENT_ID = E.ID ");
          String searchField = searchForm.getBasicSearchField();
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          sqlStat2.append("AND D.DATA_STRING " + searchForm.getBasicSearchType() + " ? ");
          if(searchForm.isSearchable()){
            sqlStat2.append("AND E.ELEMENT_ID = ? ");
          }
          preStat2 = dbConn.prepareStatement(sqlStat2.toString());
          this.setPrepareStatement(preStat2, 1, searchKeyword);  
          if(searchForm.isSearchable()){  
            this.setPrepareStatement(preStat2, 2, searchField);
          }
            
          rs2= preStat2.executeQuery();
          String submissionID = "";
          while (rs2.next()) {
            submissionID += ((submissionID.length()>0)?",":"") + getResultSetInteger(rs2, "SUBMISSION_ID");
          }
          // For Select Box, Radio Button, Check Box
          sqlStat2 = new StringBuffer();
          sqlStat2.append("SELECT DISTINCT E.SUBMISSION_ID ");
          sqlStat2.append("FROM FORM_DATA_ELEMENT E, FORM_DATA D, FORM_SELECTION_FIELD F, FORM_SELECTION_FIELD_OPTION G ");
          sqlStat2.append("WHERE D.DATA_ELEMENT_ID = E.ID AND G.SELECTION_FIELD_ID = F.ID AND E.ELEMENT_ID = F.ELEMENT_ID AND D.DATA_STRING = G.START_VALUE ");
          sqlStat2.append("AND G.LABEL " + searchForm.getBasicSearchType() + " ? ");
          if(searchForm.isSearchable()){
            sqlStat2.append("AND E.ELEMENT_ID = ? ");
          }

          preStat2 = dbConn.prepareStatement(sqlStat2.toString());
          this.setPrepareStatement(preStat2, 1, searchKeyword);  
          if(searchForm.isSearchable()){  
            this.setPrepareStatement(preStat2, 2, searchField);
          }
          rs2= preStat2.executeQuery();
          while (rs2.next()) {
            submissionID += ((submissionID.length()>0)?",":"") + getResultSetInteger(rs2, "SUBMISSION_ID");
          }

          if (!Utility.isEmpty(submissionID)) {
            sqlStat.append("           AND C.ID IN ("+submissionID+") ");
            sqlStat.append("           AND C.ID IN ("+submissionID+") ");
          }else{
            throw new ApplicationException(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR);
          }
          //}
          try { rs2.close(); } catch (Exception ignore) {} finally { rs2 = null; }
          try { preStat2.close(); } catch (Exception ignore) {} finally { preStat2 = null; }
        }
        
        sqlStat.append(attachedString);
        sqlStat = this.getFormattedSQL(sqlStat.toString());

        // Form the ORDER clause for sorting.
        if (searchForm.isSortable()) {
          String sortAttribute = searchForm.getSortAttribute();
          if (sortAttribute.indexOf(".") < 0) {
            if ("TITLE".equals(sortAttribute) ){
              sortAttribute = "UPDATE_DATE";
              searchForm.setSortAttribute("UPDATE_DATE");
              searchForm.setSortOrder("DESC");
            }
            if (sortAttribute.indexOf(".") < 0) {
              if ("WORKFLOW_CODE".equals(sortAttribute)){
                sortAttribute = "WR." + sortAttribute;
              }else{
                sortAttribute = "C." + sortAttribute;
              }
            }
          }
          sqlStat.append("ORDER BY " + sortAttribute + " " + searchForm.getSortOrder());
        }
  
        // Get total number of record return.
        sqlStatCnt = this.getSelectCountSQL(sqlStat);      
        preStatCnt = dbConn.prepareStatement(sqlStatCnt.toString());
        this.setPrepareStatement(preStatCnt, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStatCnt, 2, formRecordID);
        rsCnt = preStatCnt.executeQuery();
        if (rsCnt.next()) {
          totalNumOfRecord = rsCnt.getInt(1);
        }
                
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }

        // Retrieve the result in row basis.
        sqlStat = this.getSelectListSQL(sqlStat, startOffset, pageSize);
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 2, formRecordID);
                
        rs = preStat.executeQuery();

        this.positionCursor(rs, startOffset, pageSize);

        while (rs.next() && rowLoopCnt<pageSize) {
          FormSubmission tmpFormSubmission = new FormSubmission();

          tmpFormSubmission.setID(getResultSetInteger(rs, "ID"));
          tmpFormSubmission.setTrackID(getResultSetInteger(rs, "TRACK_ID"));
          tmpFormSubmission.setFormRecordID(getResultSetInteger(rs, "FORM_RECORD_ID"));
          tmpFormSubmission.setWorkflowRecordID(getResultSetInteger(rs, "WORKFLOW_RECORD_ID"));
          tmpFormSubmission.setWorkflowCode(getResultSetString(rs, "WORKFLOW_CODE"));
          tmpFormSubmission.setStatus(getResultSetString(rs, "STATUS"));
          tmpFormSubmission.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormSubmission.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormSubmission.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormSubmission.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpFormSubmission.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpFormSubmission.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpFormSubmission.setCreatorName(UserInfoFactory.getUserFullName(tmpFormSubmission.getCreatorID()));
          tmpFormSubmission.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormSubmission.getUpdaterID()));
          tmpFormSubmission.setRecordCount(totalNumOfRecord);

          // Retrive the workflow relationship.
//          if (isTracking) {
            com.dcivision.workflow.dao.MtmWorkflowProgressSystemObjectDAObject mtmWfProgressSysObjDAO = new com.dcivision.workflow.dao.
              MtmWorkflowProgressSystemObjectDAObject(sessionContainer, dbConn);
            com.dcivision.workflow.dao.WorkflowRecordDAObject workflowRecordDAO = new com.dcivision.workflow.dao.WorkflowRecordDAObject(sessionContainer, dbConn);

            List tmpList = mtmWfProgressSysObjDAO.getListByBeanClassNameObjectID(tmpFormSubmission.getClass().getName(), getResultSetInteger(rs, "ID"));
            List workflowRelationshipList = new ArrayList();

            if(tmpList.size()>0){
              com.dcivision.workflow.bean.MtmWorkflowProgressSystemObject tmpObj = (com.dcivision.workflow.bean.MtmWorkflowProgressSystemObject)tmpList.get(0);
              com.dcivision.workflow.bean.WorkflowRecord wfRec = (com.dcivision.workflow.bean.WorkflowRecord)workflowRecordDAO.getObjectByTrackID(tmpObj.getTrackID());
              if (wfRec != null) {
                workflowRelationshipList.add(new Object[] {wfRec, tmpObj.getTrackID()});
              }
              tmpFormSubmission.setWorkflowRelationshipList(workflowRelationshipList);
            }
            mtmWfProgressSysObjDAO=null;
            workflowRecordDAO=null;
//          }

          tmpFormSubmission.setRowNum(startOffset++);
          ++rowLoopCnt;
          result.add(tmpFormSubmission);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }
      }
    }
  }
  
  
  public synchronized List getFormSubmissionWholeFormListBySearchSection(
      AbstractSearchForm searchForm,
      boolean isTracking )
      throws ApplicationException {
    
    AbstractQuery query = QueryUtil.createQuery();
    
    PreparedStatement preStat = null;
    PreparedStatement preStatCnt = null;
    PreparedStatement preStatCnt2 = null;
    ResultSet rs = null;
    ResultSet rsCnt = null;
    ResultSet rsCnt2= null;
    StringBuffer sqlStat = new StringBuffer();
    StringBuffer sqlbindWFCnt = new StringBuffer();
    StringBuffer sqlnotbindWFCnt= new StringBuffer();
    List result = new ArrayList();
    int totalNumOfRecord = 0;
    int startOffset = TextUtility.parseInteger(searchForm.getCurStartRowNo());
    int pageSize = TextUtility.parseInteger(searchForm.getPageOffset());

    AbstractQuery bindWithWorkflowFormSubmissionListQuery = null;
    AbstractQuery notBindWithWorkflowFormSubmissionListQuery = null;

    synchronized(dbConn) {
      try {
        
        bindWithWorkflowFormSubmissionListQuery = getWorkflowBindFormSubmissionSearchListSQL(searchForm,isTracking);
        notBindWithWorkflowFormSubmissionListQuery = getNotBindWorkflowFormSubmissionSearchListSQL(searchForm,isTracking,false);
        query.subQuery(bindWithWorkflowFormSubmissionListQuery);
        query.append("\nUNION\n");
        query.subQuery(notBindWithWorkflowFormSubmissionListQuery);
        query.pack();
        sqlStat = new StringBuffer(query.toString());
        sqlStat = this.getFormattedSQL(sqlStat.toString());
        
        // Form the ORDER clause for sorting.
        if (searchForm.isSortable()) {
          String sortAttribute = searchForm.getSortAttribute();
          if (sortAttribute.indexOf(".") < 0) {
            if ("TITLE".equals(sortAttribute) ){
              sortAttribute = "UPDATE_DATE";
              searchForm.setSortAttribute("UPDATE_DATE");
              searchForm.setSortOrder("DESC");
            }
            if (sortAttribute.indexOf(".") < 0) {
              if ("WORKFLOW_CODE".equals(sortAttribute)){
                sortAttribute = "WR." + sortAttribute;
              }else{
                sortAttribute = "C." + sortAttribute;
              }
            }
          }
          sqlStat = this.getUnionOrderSQL(sqlStat, sortAttribute, searchForm.getSortOrder());
          //sqlStat.append("ORDER BY " + sortAttribute + " " + searchForm.getSortOrder());
        }
  
        // Get total number of record return.
        sqlbindWFCnt = this.getSelectCountSQL(new StringBuffer(bindWithWorkflowFormSubmissionListQuery.toString()));      
        preStatCnt = dbConn.prepareStatement(sqlbindWFCnt.toString());
        this.setPreparedStatement(preStatCnt, 1, bindWithWorkflowFormSubmissionListQuery.getAllParameters());
        rsCnt = preStatCnt.executeQuery();
        if (rsCnt.next()) {
          totalNumOfRecord = rsCnt.getInt(1);
        }        
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }
        sqlnotbindWFCnt = this.getSelectCountSQL(new StringBuffer(notBindWithWorkflowFormSubmissionListQuery.toString()));
        preStatCnt2 = dbConn.prepareStatement(sqlnotbindWFCnt.toString());
        this.setPreparedStatement(preStatCnt2, 1, notBindWithWorkflowFormSubmissionListQuery.getAllParameters());
        rsCnt2 = preStatCnt2.executeQuery();
        if (rsCnt2.next()) {
          totalNumOfRecord += rsCnt2.getInt(1);
        } 
        try { rsCnt2.close(); } catch (Exception ignore) {} finally { rsCnt2 = null; }
        try { preStatCnt2.close(); } catch (Exception ignore) {} finally { preStatCnt2 = null; }
        
        
        // Retrieve the result in row basis.
        sqlStat = this.getSelectListSQL(sqlStat, startOffset, pageSize);
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPreparedStatement(preStat, 1, query.getAllParameters());        
        
        rs = preStat.executeQuery();

        this.positionCursor(rs, startOffset, pageSize);

        while (rs.next()) {
          FormSubmission tmpFormSubmission = new FormSubmission();

          tmpFormSubmission.setID(getResultSetInteger(rs, "ID"));
          tmpFormSubmission.setTrackID(getResultSetInteger(rs, "TRACK_ID"));
          tmpFormSubmission.setFormRecordID(getResultSetInteger(rs, "FORM_RECORD_ID"));
          tmpFormSubmission.setWorkflowRecordID(getResultSetInteger(rs, "WORKFLOW_RECORD_ID"));
          tmpFormSubmission.setWorkflowCode(getResultSetString(rs, "WORKFLOW_CODE"));
          tmpFormSubmission.setStatus(getResultSetString(rs, "STATUS"));
          tmpFormSubmission.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormSubmission.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormSubmission.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormSubmission.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpFormSubmission.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpFormSubmission.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpFormSubmission.setCreatorName(UserInfoFactory.getUserFullName(tmpFormSubmission.getCreatorID()));
          tmpFormSubmission.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormSubmission.getUpdaterID()));
          tmpFormSubmission.setRecordCount(totalNumOfRecord);


            com.dcivision.workflow.dao.MtmWorkflowProgressSystemObjectDAObject mtmWfProgressSysObjDAO = new com.dcivision.workflow.dao.
              MtmWorkflowProgressSystemObjectDAObject(sessionContainer, dbConn);
            com.dcivision.workflow.dao.WorkflowRecordDAObject workflowRecordDAO = new com.dcivision.workflow.dao.WorkflowRecordDAObject(sessionContainer, dbConn);

            List tmpList = mtmWfProgressSysObjDAO.getListByBeanClassNameObjectID(tmpFormSubmission.getClass().getName(), getResultSetInteger(rs, "ID"));
            List workflowRelationshipList = new ArrayList();

            if(tmpList.size()>0){
              com.dcivision.workflow.bean.MtmWorkflowProgressSystemObject tmpObj = (com.dcivision.workflow.bean.MtmWorkflowProgressSystemObject)tmpList.get(0);
              com.dcivision.workflow.bean.WorkflowRecord wfRec = (com.dcivision.workflow.bean.WorkflowRecord)workflowRecordDAO.getObjectByTrackID(tmpObj.getTrackID());
              if (wfRec != null) {
                workflowRelationshipList.add(new Object[] {wfRec, tmpObj.getTrackID()});
              }
              tmpFormSubmission.setWorkflowRelationshipList(workflowRelationshipList);
            }
            mtmWfProgressSysObjDAO=null;
            workflowRecordDAO=null;
            
          tmpFormSubmission.setRowNum(startOffset++);
          result.add(tmpFormSubmission);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }
      }
    }
    
  }
  
  private AbstractQuery getNotBindWorkflowFormSubmissionSearchListSQL(AbstractSearchForm searchForm,boolean isTracking,boolean isWithStep){
    AbstractQuery subQuery = new SubQuery();
    
    ListFormSubmissionForm listFormSubmissionForm = (ListFormSubmissionForm)searchForm;
    String fromDate = listFormSubmissionForm.getFromDate();
    String toDate = TextUtility.dbDateAdder(listFormSubmissionForm.getToDate(), 1);
    String attachedString = "";
    String basicSearchKeyword = listFormSubmissionForm.getBasicSearchKeyword();
    String searchSubmitter = listFormSubmissionForm.getSearchSubmitter();
    boolean isShowMyForm = !Utility.isEmpty(listFormSubmissionForm.getSearchFormType()) ? true : false;
    String formRecordID = listFormSubmissionForm.getFormRecordID();
    
    
    if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_ORACLE) {
      if (!Utility.isEmpty(fromDate) && Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE >= TO_DATE('" + fromDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      } else if (Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE <= TO_DATE('" + toDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      } else if (!Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE BETWEEN TO_DATE('" + fromDate + "', 'YYYY-MM-DD HH24:MI:SS') AND TO_DATE('"+  toDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      }
    } else {
      if (!Utility.isEmpty(fromDate) && Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE >= '" + fromDate + "' ";
      } else if (Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE <= '" + toDate + "' ";
      } else if (!Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE BETWEEN '" + fromDate + "' AND '"+  toDate + "' ";
      }
    }
    
    /* Commented by Brook.Huang. We couldn't init a number value for 'TRACK_ID' and so on.
    if(isWithStep){
      subQuery.append("SELECT  C.FORM_RECORD_ID, C.ID, -1 WORKFLOW_RECORD_ID, -1 TRACK_ID, null WORKFLOW_CODE, null WORKFLOW_VERSION, -1 STEP_ID, null STEP_NAME, C.STATUS STATUS,C.RECORD_STATUS,C.UPDATE_COUNT, C.CREATOR_ID CREATOR_ID, C.CREATE_DATE CREATE_DATE, C.UPDATER_ID UPDATER_ID,C.UPDATE_DATE UPDATE_DATE, null PROGRESS_ID, null STEP_SEQ, C.STATUS SUBMISSION_STATUS ");
    }else{
      subQuery.append("SELECT  C.FORM_RECORD_ID, C.ID, -1 WORKFLOW_RECORD_ID, -1 TRACK_ID, null WORKFLOW_CODE, null WORKFLOW_VERSION, C.STATUS STATUS, C.RECORD_STATUS,C.UPDATE_COUNT, C.CREATOR_ID CREATOR_ID, C.CREATE_DATE CREATE_DATE, C.UPDATER_ID UPDATER_ID,C.UPDATE_DATE UPDATE_DATE  ");
    }
    */
 
    if(isWithStep){
      subQuery.append("SELECT  C.FORM_RECORD_ID, C.ID, -1 WORKFLOW_RECORD_ID, null TRACK_ID, null WORKFLOW_CODE, null WORKFLOW_VERSION, null STEP_ID, null STEP_NAME, C.STATUS STATUS,C.RECORD_STATUS,C.UPDATE_COUNT, C.CREATOR_ID CREATOR_ID, C.CREATE_DATE CREATE_DATE, C.UPDATER_ID UPDATER_ID,C.UPDATE_DATE UPDATE_DATE, null PROGRESS_ID, null STEP_SEQ, C.STATUS SUBMISSION_STATUS ");
    }else{
      subQuery.append("SELECT  C.FORM_RECORD_ID, C.ID, -1 WORKFLOW_RECORD_ID, null TRACK_ID, null WORKFLOW_CODE, null WORKFLOW_VERSION, C.STATUS STATUS, C.RECORD_STATUS,C.UPDATE_COUNT, C.CREATOR_ID CREATOR_ID, C.CREATE_DATE CREATE_DATE, C.UPDATER_ID UPDATER_ID,C.UPDATE_DATE UPDATE_DATE  ");
    }
    
    subQuery.append("FROM FORM_SUBMISSION C ");
    if(!Utility.isEmpty(basicSearchKeyword)){
      subQuery.append("INNER JOIN FORM_DATA_ELEMENT FE ON C.ID=FE.SUBMISSION_ID \n");
      subQuery.append("INNER JOIN FORM_DATA FD ON FE.ID=FD.DATA_ELEMENT_ID\n");
      subQuery.append("LEFT JOIN FORM_SELECTION_FIELD FS ON FE.ELEMENT_ID=FS.ELEMENT_ID \n");
      subQuery.append("LEFT JOIN FORM_SELECTION_FIELD_OPTION FO ON FS.ID=FO.SELECTION_FIELD_ID \n");
    }
//    sqlStatTmp2.append("LEFT JOIN MTM_WF_RECORD_OBJECT_LINK OL ON C.FORM_RECORD_ID = OL.OBJECT_ID AND OL.WORKFLOW_CATEGORY_ID = '10'  ");
//    sqlStatTmp2.append("LEFT JOIN WORKFLOW_RECORD WR ON WR.ID = OL.WORKFLOW_RECORD_ID  ");
//    sqlStatTmp2.append("LEFT JOIN WORKFLOW_PROGRESS WP ON SO.WORKFLOW_PROGRESS_ID = WP.ID ");
    subQuery.append("LEFT JOIN MTM_WF_PROGRESS_SYSTEM_OBJECT SO ON C.ID = SO.OBJECT_ID AND SO.BEAN_CLASS_NAME  ='com.dcivision.form.bean.FormSubmission' ");
    subQuery.append("WHERE SO.TRACK_ID IS NULL ");
    subQuery.append("AND C.RECORD_STATUS = ? AND C.FORM_RECORD_ID = ? ");

    if (isTracking || isShowMyForm) {
      subQuery.append("AND C.CREATOR_ID = '"+ sessionContainer.getUserRecordID() +"' ");
    }else{
      subQuery.append("AND  C.STATUS <> '" + FormSubmission.FORM_SUBMISSION_STATU_SAVED + "' ");
      if (!Utility.isEmpty(searchSubmitter) && !"null".equals(searchSubmitter)){
        subQuery.append("AND C.CREATOR_ID = " + searchSubmitter + " ");
      }
    }
    // Keyword search
    if(!Utility.isEmpty(basicSearchKeyword)){
      String searchField = searchForm.getBasicSearchField();
      subQuery.append("  AND ( (FS.ID IS NULL AND FD.RECORD_STATUS=? AND FD.DATA_STRING " + searchForm.getBasicSearchType() + " ?) \n");
      subQuery.append("            OR (FS.ID IS NOT NULL AND FD.RECORD_STATUS=? AND FD.DATA_STRING=FO.START_VALUE AND FO.LABEL " + searchForm.getBasicSearchType() + " ?) \n");
      subQuery.append("            )\n");
      if(!Utility.isEmpty(basicSearchKeyword) && !Utility.isEmpty(searchField)){
        subQuery.append("  AND FE.ELEMENT_ID=?\n");
      }
    }
    subQuery.append(attachedString);
    
    int i=1;
    subQuery.setParameter(i++, GlobalConstant.RECORD_STATUS_ACTIVE);
    subQuery.setParameter(i++, formRecordID);

    if(!Utility.isEmpty(basicSearchKeyword)){
      String searchField = searchForm.getBasicSearchField();
      String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
      subQuery.setParameter(i++, GlobalConstant.RECORD_STATUS_ACTIVE);
      subQuery.setParameter(i++, searchKeyword);
      subQuery.setParameter(i++, GlobalConstant.RECORD_STATUS_ACTIVE);
      subQuery.setParameter(i++, searchKeyword);
      if(!Utility.isEmpty(basicSearchKeyword) && !Utility.isEmpty(searchField)){
        subQuery.setParameter(i++, searchField);
      }
    }
    
    return subQuery;
  }
  /**
   * 
   * @param searchForm
   * @param isTracking
   * @return
   */
  private AbstractQuery getWorkflowBindFormSubmissionSearchListSQL(AbstractSearchForm searchForm,boolean isTracking){
    AbstractQuery subQuery = new SubQuery();
    
    ListFormSubmissionForm listFormSubmissionForm = (ListFormSubmissionForm)searchForm;
    String fromDate = listFormSubmissionForm.getFromDate();
    String toDate = TextUtility.dbDateAdder(listFormSubmissionForm.getToDate(), 1);
    String attachedString = "";
    String basicSearchKeyword = listFormSubmissionForm.getBasicSearchKeyword();
    String searchSubmitter = listFormSubmissionForm.getSearchSubmitter();
    boolean isShowMyForm = !Utility.isEmpty(listFormSubmissionForm.getSearchFormType()) ? true : false;
    String workflowRecordID = listFormSubmissionForm.getWorkflowRecordID();
    String formRecordID = listFormSubmissionForm.getFormRecordID();
    
    
    if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_ORACLE) {
      if (!Utility.isEmpty(fromDate) && Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE >= TO_DATE('" + fromDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      } else if (Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE <= TO_DATE('" + toDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      } else if (!Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE BETWEEN TO_DATE('" + fromDate + "', 'YYYY-MM-DD HH24:MI:SS') AND TO_DATE('"+  toDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      }
    } else {
      if (!Utility.isEmpty(fromDate) && Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE >= '" + fromDate + "' ";
      } else if (Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE <= '" + toDate + "' ";
      } else if (!Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE BETWEEN '" + fromDate + "' AND '"+  toDate + "' ";
      }
    }
    
    
    subQuery.append("SELECT DISTINCT C.FORM_RECORD_ID,  C.ID,  WR.ID WORKFLOW_RECORD_ID, SO.TRACK_ID TRACK_ID, WR.WORKFLOW_CODE, WR.WORKFLOW_VERSION, C.STATUS STATUS, C.RECORD_STATUS, C.UPDATE_COUNT, C.CREATOR_ID CREATOR_ID, C.CREATE_DATE CREATE_DATE, C.UPDATER_ID UPDATER_ID,C.UPDATE_DATE UPDATE_DATE ");
    subQuery.append("FROM FORM_SUBMISSION C ");
    if(!Utility.isEmpty(basicSearchKeyword)){
      subQuery.append("INNER JOIN FORM_DATA_ELEMENT FE ON C.ID=FE.SUBMISSION_ID \n");
      subQuery.append("INNER JOIN FORM_DATA FD ON FE.ID=FD.DATA_ELEMENT_ID\n");
      subQuery.append("LEFT JOIN FORM_SELECTION_FIELD FS ON FE.ELEMENT_ID=FS.ELEMENT_ID \n");
      subQuery.append("LEFT JOIN FORM_SELECTION_FIELD_OPTION FO ON FS.ID=FO.SELECTION_FIELD_ID \n");
    }
    subQuery.append("INNER JOIN MTM_WF_RECORD_OBJECT_LINK OL ON C.FORM_RECORD_ID = OL.OBJECT_ID AND OL.WORKFLOW_CATEGORY_ID = '" +SystemWorkflowConstant.FMB_SUBMISSION_BY_FORM+ "' ");  
    subQuery.append("INNER JOIN WORKFLOW_RECORD WR ON WR.ID = OL.WORKFLOW_RECORD_ID  ");
    subQuery.append("INNER JOIN MTM_WF_PROGRESS_SYSTEM_OBJECT SO ON C.ID = SO.OBJECT_ID AND SO.BEAN_CLASS_NAME  ='com.dcivision.form.bean.FormSubmission' ");
    subQuery.append("INNER JOIN WORKFLOW_PROGRESS WP ON WP.ID = SO.WORKFLOW_PROGRESS_ID ");
    subQuery.append("INNER JOIN WORKFLOW_STEP WS ON WS.ID = WP.WORKFLOW_STEP_ID AND WS.WORKFLOW_RECORD_ID = WR.ID ");
    
    subQuery.append("WHERE WR.RECORD_STATUS = C.RECORD_STATUS AND C.RECORD_STATUS = SO.RECORD_STATUS AND WP.RECORD_STATUS = SO.RECORD_STATUS ");
    subQuery.append("AND WP.TRACK_ID = SO.TRACK_ID ");
    subQuery.append("AND C.RECORD_STATUS = ? AND C.FORM_RECORD_ID = ? ");
    if (isTracking || isShowMyForm) {
      if (!Utility.isEmpty(workflowRecordID) && !"null".equals(workflowRecordID)){
        subQuery.append("AND WR.ID = '"+ workflowRecordID +"' ");           
      }
      subQuery.append("AND ( C.CREATOR_ID = '"+ sessionContainer.getUserRecordID() +"' ");
                  
      subQuery.append("OR C.ID IN (").subQuery(getWorkflowBindFormSubmissionListSQL(searchForm)).append(" ) ");
      
      subQuery.append(" ) ");
    }else{
      subQuery.append("AND C.STATUS <> '" + FormSubmission.FORM_SUBMISSION_STATU_SAVED + "' ");
      if (!Utility.isEmpty(searchSubmitter) && !"null".equals(searchSubmitter)){
        subQuery.append("AND WP.UPDATER_ID = " + searchSubmitter + " ");
      }
    }
    // Keyword search
    if(!Utility.isEmpty(basicSearchKeyword)){
      String searchField = searchForm.getBasicSearchField();
      //String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());

      subQuery.append("  AND ( (FS.ID IS NULL AND FD.RECORD_STATUS=? AND FD.DATA_STRING " + searchForm.getBasicSearchType() + " ?) \n");
      subQuery.append("            OR (FS.ID IS NOT NULL AND FD.RECORD_STATUS=? AND FD.DATA_STRING=FO.START_VALUE AND FO.LABEL " + searchForm.getBasicSearchType() + " ?) \n");
      subQuery.append("            )\n");
      if(!Utility.isEmpty(basicSearchKeyword) && !Utility.isEmpty(searchField)){
        subQuery.append("  AND FE.ELEMENT_ID=?\n");
      }
    }
    subQuery.append(attachedString);
    
    int i=1;
    subQuery.setParameter(i++, GlobalConstant.RECORD_STATUS_ACTIVE);
    subQuery.setParameter(i++, formRecordID);
  
    if(!Utility.isEmpty(basicSearchKeyword)){
      String searchField = searchForm.getBasicSearchField();
      String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
      subQuery.setParameter(i++, GlobalConstant.RECORD_STATUS_ACTIVE);
      subQuery.setParameter(i++, searchKeyword);
      subQuery.setParameter(i++, GlobalConstant.RECORD_STATUS_ACTIVE);
      subQuery.setParameter(i++, searchKeyword);
      if(!Utility.isEmpty(basicSearchKeyword) && !Utility.isEmpty(searchField)){
        subQuery.setParameter(i++, searchField);
      }
    }
    
    subQuery.pack();
    return subQuery;
  }
  /**
   * 
   * @param searchForm
   * @return
   */
  private AbstractQuery getWorkflowBindFormSubmissionListSQL(AbstractSearchForm searchForm){
    AbstractQuery subQuery = new SubQuery();
    String formRecordID = ((ListFormSubmissionForm)searchForm).getFormRecordID();
    String workflowRecordID =((ListFormSubmissionForm)searchForm).getWorkflowRecordID();
    subQuery.append("SELECT DISTINCT C.ID ");             
    subQuery.append("FROM FORM_SUBMISSION C "); 
    subQuery.append("INNER JOIN MTM_WF_RECORD_OBJECT_LINK OL ON C.FORM_RECORD_ID = OL.OBJECT_ID AND OL.WORKFLOW_CATEGORY_ID = '10' "); 
    subQuery.append("INNER JOIN WORKFLOW_RECORD WR ON WR.ID = OL.WORKFLOW_RECORD_ID ");
    subQuery.append("INNER JOIN WORKFLOW_STEP WS ON WR.ID = WS.WORKFLOW_RECORD_ID AND WS.STEP_SEQ <> '999999999' ");
    subQuery.append("INNER JOIN WORKFLOW_PROGRESS WP ON WP.WORKFLOW_STEP_ID = WS.ID ");
    subQuery.append("INNER JOIN MTM_WF_PROGRESS_SYSTEM_OBJECT SO ON C.ID = SO.OBJECT_ID AND SO.BEAN_CLASS_NAME  ='com.dcivision.form.bean.FormSubmission' ");            
    subQuery.append("INNER JOIN MTM_WF_PROGRESS_USER_RECORD MUR ON MUR.WORKFLOW_PROGRESS_ID = WP.ID ");            
    subQuery.append("WHERE WS.RECORD_STATUS = WR.RECORD_STATUS AND WS.RECORD_STATUS = WR.RECORD_STATUS AND C.RECORD_STATUS = WS.RECORD_STATUS  ");
    subQuery.append("AND WP.TRACK_ID = SO.TRACK_ID ");
    subQuery.append("AND C.RECORD_STATUS = ? AND C.FORM_RECORD_ID = ? ");              
    subQuery.append("AND MUR.UPDATER_ID = '"+ sessionContainer.getUserRecordID() +"' ");
    if (!Utility.isEmpty(workflowRecordID) && !"null".equals(workflowRecordID)){
      subQuery.append("AND WR.ID = '"+ workflowRecordID +"' ");
    }
   
    subQuery.setParameter(1, GlobalConstant.RECORD_STATUS_ACTIVE);
    subQuery.setParameter(2, formRecordID);
    
    return subQuery;
  }
  

  /**
   * Get the count of form submission by submitted date range
   * @param formRecordID
   * @param fromDate
   * @param toDate
   * @return int count
   * @throws ApplicationException
   */
  public int getFormSubmissionCountBySubmittedDateRange(
        String formRecordID,
        AbstractActionForm searchForm) throws ApplicationException {
    PreparedStatement preStatCnt = null;
    PreparedStatement preStat2 = null;
    ResultSet rsCnt = null;
    ResultSet rs2 = null;
    StringBuffer sqlStat = new StringBuffer();
    StringBuffer sqlStat2 = new StringBuffer();
    List result = new ArrayList();
    int totalNumOfRecord = 0;

    MaintFormSubmissionForm maintFormSubmissionForm = (MaintFormSubmissionForm)searchForm;
    String fromDate = maintFormSubmissionForm.getFromDate();
    String toDate = TextUtility.dbDateAdder(maintFormSubmissionForm.getToDate(), 1);
    String basicSearchKeyword = maintFormSubmissionForm.getBasicSearchKeyword();
    String searchStatus = maintFormSubmissionForm.getSearchStatus();
    String searchSubmitter = maintFormSubmissionForm.getSearchSubmitter();


    String attachedString = "";
    if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_ORACLE) {
    	if (!Utility.isEmpty(fromDate) && Utility.isEmpty(toDate)) {
        attachedString = " AND A.CREATE_DATE >= TO_DATE('" + fromDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      } else if (Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND A.CREATE_DATE <= TO_DATE('" + toDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      } else if (!Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND A.CREATE_DATE BETWEEN TO_DATE('" + fromDate + "', 'YYYY-MM-DD HH24:MI:SS') AND TO_DATE('" +
            toDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      }
    } else {
    	if (!Utility.isEmpty(fromDate) && Utility.isEmpty(toDate)) {
        attachedString = " AND A.CREATE_DATE >= '" + fromDate + "' ";
      } else if (Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND A.CREATE_DATE <= '" + toDate + "' ";
      } else if (!Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND A.CREATE_DATE BETWEEN '" + fromDate + "' AND '" +
            toDate + "' ";
      }
    }


    synchronized (dbConn) {
      try {
        sqlStat.append("SELECT COUNT(*) ");
        sqlStat.append("FROM   FORM_SUBMISSION A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? AND A.FORM_RECORD_ID = ? ");
        if (!Utility.isEmpty(searchStatus)) {
          sqlStat.append("AND A.STATUS = '" + searchStatus + "' ");
        }else{
          sqlStat.append("AND A.STATUS <> '" + FormSubmission.FORM_SUBMISSION_STATU_SAVED + "' ");
        }
        if (!Utility.isEmpty(searchSubmitter)) {
          sqlStat.append("AND A.CREATOR_ID = "+ searchSubmitter +" ");
        }
       //search submissionID
        if(!Utility.isEmpty(basicSearchKeyword)){
          // For Text Box
            sqlStat2.append("SELECT DISTINCT E.SUBMISSION_ID FROM FORM_DATA_ELEMENT E, FORM_DATA D ");
          sqlStat2.append("WHERE D.DATA_ELEMENT_ID = E.ID ");
          String searchField = maintFormSubmissionForm.getBasicSearchField();
          String searchKeyword = this.getFormattedKeyword(maintFormSubmissionForm.getBasicSearchKeyword(), maintFormSubmissionForm.getBasicSearchType());
          sqlStat2.append("AND D.DATA_STRING " + maintFormSubmissionForm.getBasicSearchType() + " ? ");
          if(!Utility.isEmpty(basicSearchKeyword) && !Utility.isEmpty(searchField)){
            sqlStat2.append("AND E.ELEMENT_ID = ? ");
          }
          preStat2 = dbConn.prepareStatement(sqlStat2.toString());
          this.setPrepareStatement(preStat2, 1, searchKeyword);  
          if(!Utility.isEmpty(basicSearchKeyword) && !Utility.isEmpty(searchField)){
            this.setPrepareStatement(preStat2, 2, searchField);
          }
          rs2= preStat2.executeQuery();
          String submissionID = "";
          while (rs2.next()) {
            submissionID += ((submissionID.length()>0)?",":"") + getResultSetInteger(rs2, "SUBMISSION_ID");
          }
          // For Select Box, Radio Button, Check Box
          sqlStat2 = new StringBuffer();
          sqlStat2.append("SELECT DISTINCT E.SUBMISSION_ID ");
          sqlStat2.append("FROM FORM_DATA_ELEMENT E, FORM_DATA D, FORM_SELECTION_FIELD F, FORM_SELECTION_FIELD_OPTION G ");
          sqlStat2.append("WHERE D.DATA_ELEMENT_ID = E.ID AND G.SELECTION_FIELD_ID = F.ID AND E.ELEMENT_ID = F.ELEMENT_ID AND D.DATA_STRING = G.START_VALUE ");
          sqlStat2.append("AND G.LABEL " + maintFormSubmissionForm.getBasicSearchType() + " ? ");
          if(!Utility.isEmpty(basicSearchKeyword) && !Utility.isEmpty(searchField)){
            sqlStat2.append("AND E.ELEMENT_ID = ? ");
          }
          preStat2 = dbConn.prepareStatement(sqlStat2.toString());
          this.setPrepareStatement(preStat2, 1, searchKeyword);  
          if(!Utility.isEmpty(basicSearchKeyword) && !Utility.isEmpty(searchField)){
            this.setPrepareStatement(preStat2, 2, searchField);
          }
          rs2= preStat2.executeQuery();
          while (rs2.next()) {
            submissionID += ((submissionID.length()>0)?",":"") + getResultSetInteger(rs2, "SUBMISSION_ID");
          }

          if (!Utility.isEmpty(submissionID)) {
            sqlStat.append("           AND A.ID IN ("+submissionID+") ");
          }else{
            throw new ApplicationException(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR);
          }
          //}
          try { rs2.close(); } catch (Exception ignore) {} finally { rs2 = null; }
          try { preStat2.close(); } catch (Exception ignore) {} finally { preStat2 = null; }
        }


        sqlStat.append(attachedString);
        // Get total number of record return.
        preStatCnt = dbConn.prepareStatement(sqlStat.toString());
        preStatCnt.setString(1,GlobalConstant.RECORD_STATUS_ACTIVE);
        preStatCnt.setString(2,formRecordID);

        rsCnt = preStatCnt.executeQuery();
        if (rsCnt.next()) {
          totalNumOfRecord = rsCnt.getInt(1);
        }
        return (totalNumOfRecord);
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle,
                                       sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try {
          rsCnt.close();
        } catch (Exception ignore) {} finally {
          rsCnt = null;
        }
        try {
          preStatCnt.close();
        } catch (Exception ignore) {} finally {
          preStatCnt = null;
        }
      }
    }
  }


  public synchronized void updateStatusByID(Integer objID, String status) throws ApplicationException {
  PreparedStatement preStat = null;
  StringBuffer sqlStat = new StringBuffer();

  synchronized(dbConn) {
    try {
      int updateCnt = 0;
      sqlStat.append("UPDATE FORM_SUBMISSION ");
      sqlStat.append("SET  STATUS=? ");
      sqlStat.append("WHERE  ID=? ");
      preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
      setPrepareStatement(preStat, 1, status);
      setPrepareStatement(preStat, 2, objID);
      updateCnt = preStat.executeUpdate();
    } catch (SQLException sqle) {
      log.error(sqle, sqle);
      throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.DB_DELETE_ERROR, e);
    } finally {
      try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
    }
  }
}

  public synchronized void updateDmsParentIDByID(Integer objID, Integer dmsParentID) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();

    synchronized(dbConn) {
      try {
        int updateCnt = 0;
        sqlStat.append("UPDATE FORM_SUBMISSION ");
        sqlStat.append("SET  DMS_PARENT_ID=? ");
        sqlStat.append("WHERE  ID=? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setPrepareStatement(preStat, 1, dmsParentID);
        setPrepareStatement(preStat, 2, objID);
        updateCnt = preStat.executeUpdate();
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_DELETE_ERROR, e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }
  
  public synchronized boolean isUniqueField(Integer elementID, String dataString, String formSubmissionID)throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    ResultSet rsCnt = null;
    StringBuffer sqlStat = new StringBuffer();
    boolean isUniqueField = true;
    
    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT COUNT(*) FROM FORM_DATA_ELEMENT A, FORM_DATA B, FORM_SUBMISSION C ");
        sqlStat.append("WHERE B.DATA_ELEMENT_ID = A.ID ");                           
        sqlStat.append("AND A.SUBMISSION_ID = C.ID ");
        sqlStat.append("AND A.RECORD_STATUS = B.RECORD_STATUS AND C.RECORD_STATUS = A.RECORD_STATUS ");
        sqlStat.append("AND A.ELEMENT_ID = ?  ");
        sqlStat.append("AND B.DATA_STRING = ? ");
        sqlStat.append("AND A.RECORD_STATUS = ? ");
        sqlStat.append("AND C.STATUS <> ? ");
        
        if(!Utility.isEmpty(formSubmissionID)){
          sqlStat.append("AND C.ID <> " + new Integer(formSubmissionID) + " ");
        }   
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
       
        this.setPrepareStatement(preStat, 1, elementID);
        this.setPrepareStatement(preStat, 2, dataString);
        this.setPrepareStatement(preStat, 3, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 4, FormSubmission.FORM_SUBMISSION_STATU_SAVED);
        rs= preStat.executeQuery();             
        if (rs.next() && rs.getInt(1)>0 ) {
          isUniqueField = false;
        }     
        return (isUniqueField);
      } catch (java.sql.SQLException sqle) {
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { sqlStat = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  /**
   * get Form Task List
   * @param searchForm
   * @return
   * @throws ApplicationException
   */    
  public synchronized List getFormTaskList(AbstractSearchForm searchForm) throws ApplicationException {
    PreparedStatement preStat = null;
    PreparedStatement preStatCnt = null;
    ResultSet rs = null;
    ResultSet rsCnt = null;
    StringBuffer sqlStat = new StringBuffer();
    StringBuffer sqlStatCnt = new StringBuffer();
    List result = new ArrayList();
    int totalNumOfRecord = 0;
    int rowLoopCnt = 0;
    int startOffset = TextUtility.parseInteger(searchForm.getCurStartRowNo());
    int pageSize = TextUtility.parseInteger(searchForm.getPageOffset());
    
    ListFormSubmissionForm actionForm = (ListFormSubmissionForm)searchForm;
    synchronized(dbConn) {
      try {
        sqlStat.append(" SELECT A.ID, A.TRACK_ID, A.FORM_RECORD_ID, A.WORKFLOW_RECORD_ID, A.IP, A.GUEST_NAME, A.EMAIL, A.CONTACT_INFO, A.DMS_PARENT_ID, A.STATUS, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE, B.FORM_CODE, B.TITLE, B.FORM_VERSION, B.FORM_TYPE, B.FORM_DOC_ID, C.WORKFLOW_CODE, C.WORKFLOW_VERSION ");
        sqlStat.append(" FROM   FORM_SUBMISSION A, FORM_RECORD B,  WORKFLOW_RECORD C ");
        sqlStat.append(" WHERE  A.FORM_RECORD_ID = B.ID ");
        sqlStat.append(" AND A.WORKFLOW_RECORD_ID = C.ID ");
        sqlStat.append(" AND A.RECORD_STATUS = B.RECORD_STATUS ");
        sqlStat.append(" AND A.RECORD_STATUS = C.RECORD_STATUS ");
        sqlStat.append(" AND A.RECORD_STATUS = ? ");
        sqlStat.append(" AND A.STATUS = ? ");
        //sqlStat.append(" ORDER BY A.TRACK_ID, A.ID ");

        // Form the WHERE clause for filtering.
        if (searchForm.isSearchable()) {
          String searchField = getSearchColumn(searchForm.getBasicSearchField());
          sqlStat.append("AND  " + searchField + " " + searchForm.getBasicSearchType() + " ? ");
        }

        if (!Utility.isEmpty(actionForm.getSearchFormType())){
          sqlStat.append("AND B.FORM_TYPE = '" + actionForm.getSearchFormType() + "' ");
        }
        
        if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_ORACLE) {            
          if (!Utility.isEmpty(actionForm.getFromDate())) {
            sqlStat.append(" AND A.UPDATE_DATE >= to_date('" + actionForm.getFromDate() + "', 'YYYY-MM-DD HH24:MI:SS') ");
          }
          if (!Utility.isEmpty(actionForm.getToDate())) {
            sqlStat.append(" AND A.UPDATE_DATE <= to_date('" + TextUtility.dbDateAdder(actionForm.getToDate(), 1) + "', 'YYYY-MM-DD HH24:MI:SS') ");
          }
        } else {
          if (!Utility.isEmpty(actionForm.getFromDate())) {
            sqlStat.append(" AND A.UPDATE_DATE >= '" + actionForm.getFromDate() + "' ");
          }
          if (!Utility.isEmpty(actionForm.getToDate())) {
            sqlStat.append(" AND A.UPDATE_DATE <= '" +  TextUtility.dbDateAdder(actionForm.getToDate(), 1) + "' ");
          }
           
        }
        
        //format the sql for any 'LIKE' statement contained
        sqlStat = this.getFormattedSQL(sqlStat.toString());

        // Form the ORDER clause for sorting.
        if (searchForm.isSortable()) {
          String sortAttribute = searchForm.getSortAttribute();
          if("TITLE".equals(sortAttribute) ){
            sortAttribute = "B." + sortAttribute;
          } else if (sortAttribute.indexOf(".") < 0) {
            sortAttribute = "A." + sortAttribute;
          }
          sqlStat.append("ORDER BY " + sortAttribute + " " + searchForm.getSortOrder());
        }               

        // Get total number of record return.
        sqlStatCnt = this.getSelectCountSQL(sqlStat);
        preStatCnt = dbConn.prepareStatement(sqlStatCnt.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStatCnt, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStatCnt, 2, FormSubmission.FORM_SUBMISSION_STATU_PENDING);
        
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          this.setPrepareStatement(preStatCnt, 3, searchKeyword);
        }
        rsCnt = preStatCnt.executeQuery();
        if (rsCnt.next()) {
          totalNumOfRecord = rsCnt.getInt(1);
        }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }

        // Retrieve the result in row basis.
        sqlStat = this.getSelectListSQL(sqlStat, startOffset, pageSize);
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 2, FormSubmission.FORM_SUBMISSION_STATU_PENDING);
        
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          this.setPrepareStatement(preStat, 3, searchKeyword);
        }
        rs = preStat.executeQuery();

        this.positionCursor(rs, startOffset, pageSize);

        while (rs.next() && rowLoopCnt<pageSize) {
          FormSubmission tmpFormSubmission = new FormSubmission();
          tmpFormSubmission.setID(getResultSetInteger(rs, "ID"));
          tmpFormSubmission.setTrackID(getResultSetInteger(rs, "TRACK_ID"));
          tmpFormSubmission.setFormRecordID(getResultSetInteger(rs, "FORM_RECORD_ID"));
          tmpFormSubmission.setWorkflowRecordID(getResultSetInteger(rs, "WORKFLOW_RECORD_ID"));
          tmpFormSubmission.setIp(getResultSetString(rs, "IP"));
          tmpFormSubmission.setGuestName(getResultSetString(rs, "GUEST_NAME"));
          tmpFormSubmission.setEmail(getResultSetString(rs, "EMAIL"));
          tmpFormSubmission.setContactInfo(getResultSetString(rs, "CONTACT_INFO"));
          tmpFormSubmission.setDmsParentID(getResultSetInteger(rs, "DMS_PARENT_ID"));
          tmpFormSubmission.setStatus(getResultSetString(rs, "STATUS"));
          tmpFormSubmission.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormSubmission.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormSubmission.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormSubmission.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpFormSubmission.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpFormSubmission.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          
          tmpFormSubmission.setFormCode(getResultSetString(rs, "FORM_CODE"));
          tmpFormSubmission.setTitle(getResultSetString(rs, "TITLE"));
          tmpFormSubmission.setFormVersion(getResultSetString(rs, "FORM_VERSION"));
          tmpFormSubmission.setFormType(getResultSetString(rs, "FORM_TYPE"));
          tmpFormSubmission.setFormDocID(getResultSetInteger(rs, "FORM_DOC_ID"));
          tmpFormSubmission.setWorkflowCode(getResultSetString(rs, "WORKFLOW_CODE"));
          tmpFormSubmission.setWorkflowVersion(getResultSetString(rs, "WORKFLOW_VERSION"));
          
          tmpFormSubmission.setCreatorName(UserInfoFactory.getUserFullName(tmpFormSubmission.getCreatorID()));
          tmpFormSubmission.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormSubmission.getUpdaterID()));
          tmpFormSubmission.setRecordCount(totalNumOfRecord);
          tmpFormSubmission.setRowNum(startOffset++);
          ++rowLoopCnt;
          result.add(tmpFormSubmission);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }
      }
    }
  }
  
  /**
   * get form submission list by track ID & status.
   * @param trackID
   * @param status
   * @return
   * @throws ApplicationException
   */
  public synchronized List getListByTrackIDStatus(Integer trackID, String status) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.TRACK_ID, A.FORM_RECORD_ID, A.WORKFLOW_RECORD_ID, A.IP, A.GUEST_NAME, A.EMAIL, A.CONTACT_INFO, A.DMS_PARENT_ID, A.STATUS, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   FORM_SUBMISSION A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? ");
        sqlStat.append("AND  A.TRACK_ID = ? ");
        
        if(!Utility.isEmpty(status)){
          sqlStat.append("AND  A.STATUS = ? ");
        }
        
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 2, trackID);
        
        if(!Utility.isEmpty(status)){
          this.setPrepareStatement(preStat, 3, status);
        }  
        
        rs = preStat.executeQuery();
        while (rs.next()) {
          FormSubmission tmpFormSubmission = new FormSubmission();
          tmpFormSubmission.setID(getResultSetInteger(rs, "ID"));
          tmpFormSubmission.setTrackID(getResultSetInteger(rs, "TRACK_ID"));
          tmpFormSubmission.setFormRecordID(getResultSetInteger(rs, "FORM_RECORD_ID"));
          tmpFormSubmission.setWorkflowRecordID(getResultSetInteger(rs, "WORKFLOW_RECORD_ID"));
          tmpFormSubmission.setIp(getResultSetString(rs, "IP"));
          tmpFormSubmission.setGuestName(getResultSetString(rs, "GUEST_NAME"));
          tmpFormSubmission.setEmail(getResultSetString(rs, "EMAIL"));
          tmpFormSubmission.setContactInfo(getResultSetString(rs, "CONTACT_INFO"));
          tmpFormSubmission.setDmsParentID(getResultSetInteger(rs, "DMS_PARENT_ID"));
          tmpFormSubmission.setStatus(getResultSetString(rs, "STATUS"));
          tmpFormSubmission.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormSubmission.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormSubmission.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormSubmission.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpFormSubmission.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpFormSubmission.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpFormSubmission.setCreatorName(UserInfoFactory.getUserFullName(tmpFormSubmission.getCreatorID()));
          tmpFormSubmission.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormSubmission.getUpdaterID()));
          result.add(tmpFormSubmission);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }
  
  /**
   * get object by trackID ,formRecordID ,workflowRecordID
   * @param trackID
   * @param formRecordID
   * @param workflowRecordID
   * @return
   * @throws ApplicationException
   */    
  public synchronized AbstractBaseObject getObjectByTrackIDFormRecordIDWorkflowRecordID(
  		Integer trackID,
			Integer formRecordID, 
			Integer workflowRecordID) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.TRACK_ID, A.FORM_RECORD_ID, A.WORKFLOW_RECORD_ID, A.IP, A.GUEST_NAME, A.EMAIL, A.CONTACT_INFO, A.DMS_PARENT_ID, A.STATUS, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   FORM_SUBMISSION A ");
        sqlStat.append("WHERE  A.TRACK_ID = ? AND A.FORM_RECORD_ID = ? AND A.WORKFLOW_RECORD_ID = ? AND A.RECORD_STATUS = ? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, trackID);
        this.setPrepareStatement(preStat, 2, formRecordID);
        this.setPrepareStatement(preStat, 3, workflowRecordID);
        this.setPrepareStatement(preStat, 4, GlobalConstant.RECORD_STATUS_ACTIVE);
        rs = preStat.executeQuery();
        if (rs.next()) {
          FormSubmission tmpFormSubmission = new FormSubmission();
          tmpFormSubmission.setID(getResultSetInteger(rs, "ID"));
          tmpFormSubmission.setTrackID(getResultSetInteger(rs, "TRACK_ID"));
          tmpFormSubmission.setFormRecordID(getResultSetInteger(rs, "FORM_RECORD_ID"));
          tmpFormSubmission.setWorkflowRecordID(getResultSetInteger(rs, "WORKFLOW_RECORD_ID"));
          tmpFormSubmission.setIp(getResultSetString(rs, "IP"));
          tmpFormSubmission.setGuestName(getResultSetString(rs, "GUEST_NAME"));
          tmpFormSubmission.setEmail(getResultSetString(rs, "EMAIL"));
          tmpFormSubmission.setContactInfo(getResultSetString(rs, "CONTACT_INFO"));
          tmpFormSubmission.setDmsParentID(getResultSetInteger(rs, "DMS_PARENT_ID"));
          tmpFormSubmission.setStatus(getResultSetString(rs, "STATUS"));
          tmpFormSubmission.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormSubmission.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormSubmission.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormSubmission.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpFormSubmission.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpFormSubmission.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpFormSubmission.setCreatorName(UserInfoFactory.getUserFullName(tmpFormSubmission.getCreatorID()));
          tmpFormSubmission.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormSubmission.getUpdaterID()));
          return(tmpFormSubmission);
        } else {
          throw new ApplicationException(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }
 
  /**
   * get the form submission list by the search section for Tracking
   * @param searchForm
   * @return
   * @throws ApplicationException
   */
  public synchronized List getFormSubmissionListByAdvanceSearchSectionForTracking(
      AbstractSearchForm searchForm )
      throws ApplicationException {
    ListFormSubmissionForm listForm = (ListFormSubmissionForm)searchForm;
    return this.getFormSubmissionListByAdvanceSearchSection(searchForm,true);
  }
  
  public synchronized List getFormSubmissionListByAdvanceSearchSectionForMonitor(
      AbstractSearchForm searchForm )
      throws ApplicationException {
    ListFormSubmissionForm listForm = (ListFormSubmissionForm)searchForm;
    return this.getFormSubmissionListByAdvanceSearchSection(searchForm,false);
  }
  
  /**
   * get the form submission list by the advance search section
   * @param searchForm
   * @return
   * @throws ApplicationException
   */
  public synchronized List getFormSubmissionListByAdvanceSearchSection(
      AbstractSearchForm searchForm,
      boolean isTracking )
      throws ApplicationException {
    String formRecordID = ((ListFormSubmissionForm)searchForm).getFormRecordID();
    PreparedStatement preStat = null;
    PreparedStatement preStat2 = null;
    PreparedStatement preStatCnt = null;
    ResultSet rs = null;
    ResultSet rs2 = null;
    ResultSet rsCnt = null;
    StringBuffer sqlStat = new StringBuffer();
    StringBuffer sqlStatCnt = new StringBuffer("SELECT COUNT(*) FROM FORM_SUBMISSION C WHERE C.RECORD_STATUS = ? AND C.FORM_RECORD_ID = ? ");
    StringBuffer attachedSqlStat = new StringBuffer();
    List result = new ArrayList();
    int totalNumOfRecord = 0;
    int rowLoopCnt = 0;
    int startOffset = TextUtility.parseInteger(searchForm.getCurStartRowNo());
    int pageSize = TextUtility.parseInteger(searchForm.getPageOffset());

    ListFormSubmissionForm listFormSubmissionForm = (ListFormSubmissionForm)searchForm;
    String fromDate = listFormSubmissionForm.getFromDate();
    String toDate = TextUtility.dbDateAdder(listFormSubmissionForm.getToDate(), 1);
    String searchSubmitter = listFormSubmissionForm.getSearchSubmitter();
    String attachedString = "";
    String attachedString2 = "";

    Map searchPanelMap = new HashMap();
    Object[] textBoxObject = new Object[3];
    Object[] datePickerObject = new Object[3];
    Object[] selectionObject = new Object[2];
    searchPanelMap = listFormSubmissionForm.getSearchPanelMap();
    textBoxObject = (Object[])searchPanelMap.get("textBoxObject");
    selectionObject = (Object[])searchPanelMap.get("selectionObject");
    datePickerObject = (Object[])searchPanelMap.get("datePickerObject");
    
    
    StringBuffer sqlStat2 = new StringBuffer();


    if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_ORACLE) {
        if (!Utility.isEmpty(fromDate) && Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE >= TO_DATE('" + fromDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      } else if (Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE <= TO_DATE('" + toDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      } else if (!Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE BETWEEN TO_DATE('" + fromDate + "', 'YYYY-MM-DD HH24:MI:SS') AND TO_DATE('"+  toDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      }
    } else {
        if (!Utility.isEmpty(fromDate) && Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE >= '" + fromDate + "' ";
      } else if (Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE <= '" + toDate + "' ";
      } else if (!Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND C.UPDATE_DATE BETWEEN '" + fromDate + "' AND '"+  toDate + "' ";
      }
    }
    
    
    if (!Utility.isEmpty(datePickerObject) && !"null".equals(datePickerObject)){  
      Object[] elementIDArr = (Object[])datePickerObject[0];
      Object[] fromDateArr = (Object[])datePickerObject[1];
      Object[] toDateArr = (Object[])datePickerObject[2];
      if (!Utility.isEmpty(elementIDArr) && !"null".equals(elementIDArr)){
        for (int i=0; i<elementIDArr.length; i++){               
          if (!Utility.isEmpty(elementIDArr[i].toString()) ){
            if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_ORACLE) {
              if (!Utility.isEmpty(fromDateArr[i].toString()) && Utility.isEmpty(toDateArr[i].toString())) {
                attachedString2 = " AND D.DATA_STRING >= TO_DATE('" + fromDateArr[i] + "', 'YYYY-MM-DD HH24:MI:SS') AND E.ELEMENT_ID = " + elementIDArr[i] + " ";
              } else if (Utility.isEmpty(fromDateArr[i].toString()) && !Utility.isEmpty(toDateArr[i].toString())) {
                attachedString2 = " AND D.DATA_STRING <= TO_DATE('" + TextUtility.dbDateAdder(toDateArr[i].toString(),1) + "', 'YYYY-MM-DD HH24:MI:SS') AND E.ELEMENT_ID = " + elementIDArr[i] + " ";
              } else if (!Utility.isEmpty(fromDateArr[i].toString()) && !Utility.isEmpty(toDateArr[i].toString())) {
                attachedString2 = " AND D.DATA_STRING BETWEEN TO_DATE('" + fromDateArr[i] + "', 'YYYY-MM-DD HH24:MI:SS') AND TO_DATE('"+  TextUtility.dbDateAdder(toDateArr[i].toString(),1) + "', 'YYYY-MM-DD HH24:MI:SS') AND E.ELEMENT_ID = " + elementIDArr[i] + " ";
              }
            } else {
              if (!Utility.isEmpty(fromDateArr[i].toString()) && Utility.isEmpty(toDateArr[i].toString())) {
                attachedString2 = " AND D.DATA_STRING >= '" + fromDateArr[i] + "' AND E.ELEMENT_ID = " + elementIDArr[i] + " ";
              } else if (Utility.isEmpty(fromDateArr[i].toString()) && !Utility.isEmpty(toDateArr[i].toString())) {
                attachedString2 = " AND D.DATA_STRING <= '" + TextUtility.dbDateAdder(toDateArr[i].toString(),1) + "' AND E.ELEMENT_ID = " + elementIDArr[i] + " ";
              } else if (!Utility.isEmpty(fromDateArr[i].toString()) && !Utility.isEmpty(toDateArr[i].toString())) {
                attachedString2 = " AND D.DATA_STRING BETWEEN '" + fromDateArr[i] + "' AND '"+  TextUtility.dbDateAdder(toDateArr[i].toString(),1) + "' AND E.ELEMENT_ID = " + elementIDArr[i] + " ";
              }
            }
            if (!Utility.isEmpty(attachedString2)){
              sqlStat2.append("SELECT DISTINCT E.SUBMISSION_ID FROM FORM_DATA_ELEMENT E, FORM_DATA D ");
              sqlStat2.append("WHERE D.DATA_ELEMENT_ID = E.ID ");  
              sqlStat2.append(attachedString2);  
              try {
              preStat2 = dbConn.prepareStatement(sqlStat2.toString());
              rs2= preStat2.executeQuery();
              String submissionID = "";
              while (rs2.next()) {
                submissionID += ((submissionID.length()>0)?",":"") + getResultSetInteger(rs2, "SUBMISSION_ID");
              }    
              submissionID = !Utility.isEmpty(submissionID) ? submissionID : "-1";
              attachedSqlStat.append("AND C.ID in ("+submissionID+") "); 
              sqlStatCnt.append("AND C.ID in ("+submissionID+") "); 
              sqlStat2 = new StringBuffer();
              } catch (ApplicationException appEx) {
                throw appEx;
              } catch (SQLException sqle) {
                log.error(sqle, sqle);
                throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
              } catch (Exception e) {
                log.error(e, e);
                throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
              }
            }
          }
        }
      } 
    }

    synchronized(dbConn) {
      try {
//        sqlStat.append("SELECT DISTINCT A.FORM_CODE, A.FORM_VERSION, A.TITLE,C.ID, C.TRACK_ID, C.FORM_RECORD_ID, C.WORKFLOW_RECORD_ID, C.IP,C.GUEST_NAME,C.EMAIL,C.CONTACT_INFO, C.DMS_PARENT_ID, C.STATUS,C.RECORD_STATUS,C.UPDATE_COUNT, C.CREATOR_ID, C.CREATE_DATE, C.UPDATER_ID,C.UPDATE_DATE ");
//        sqlStat.append("FROM   FORM_RECORD A, FORM_SUBMISSION C, FORM_DATA_ELEMENT E, FORM_DATA D ");
//        sqlStat.append("WHERE  A.ID = C.FORM_RECORD_ID ");
//        sqlStat.append("AND D.DATA_ELEMENT_ID = E.ID AND C.ID = E.SUBMISSION_ID ");
//        sqlStat.append("AND A.RECORD_STATUS = E.RECORD_STATUS AND A.RECORD_STATUS = D.RECORD_STATUS AND A.RECORD_STATUS = C.RECORD_STATUS ");
//        sqlStat.append("AND C.RECORD_STATUS = ? AND C.FORM_RECORD_ID = ? ");
        sqlStat.append("SELECT DISTINCT A.FORM_CODE, A.FORM_VERSION, A.TITLE,C.ID, C.TRACK_ID, C.FORM_RECORD_ID, C.WORKFLOW_RECORD_ID, C.IP,C.GUEST_NAME,C.EMAIL,C.CONTACT_INFO, C.DMS_PARENT_ID, C.STATUS,C.RECORD_STATUS,C.UPDATE_COUNT, C.CREATOR_ID, C.CREATE_DATE, C.UPDATER_ID,C.UPDATE_DATE ");
        sqlStat.append("FROM   FORM_RECORD A, FORM_SUBMISSION C ");
        sqlStat.append("WHERE  A.ID = C.FORM_RECORD_ID ");        
        sqlStat.append("AND A.RECORD_STATUS = C.RECORD_STATUS ");
        sqlStat.append("AND C.RECORD_STATUS = ? AND C.FORM_RECORD_ID = ? ");
        if (isTracking) {
          sqlStat.append("AND C.CREATOR_ID = '"+ sessionContainer.getUserRecordID() +"' ");
        }else{
          sqlStat.append("AND C.STATUS <> '" + FormSubmission.FORM_SUBMISSION_STATU_SAVED + "' ");
          if (!Utility.isEmpty(searchSubmitter) && !"null".equals(searchSubmitter)){
            sqlStat.append("AND C.CREATOR_ID = " + searchSubmitter + " ");
          }
        } 
        //
        
        Object[] elementIDArr = (Object[])textBoxObject[0];
        Object[] typeArr = (Object[])textBoxObject[1];
        Object[] keywordArr = (Object[])textBoxObject[2];
        if (!Utility.isEmpty(elementIDArr) && !"null".equals(elementIDArr)){
          for (int i=0; i<elementIDArr.length; i++){               
            if (!Utility.isEmpty(elementIDArr[i].toString()) ){         
              if (!Utility.isEmpty(keywordArr[i].toString())){
                sqlStat2.append("SELECT DISTINCT E.SUBMISSION_ID FROM FORM_DATA_ELEMENT E, FORM_DATA D ");
                sqlStat2.append("WHERE D.DATA_ELEMENT_ID = E.ID ");             
                String searchKeyword = this.getFormattedKeyword(keywordArr[i].toString(), typeArr[i].toString());
                sqlStat2.append("AND D.DATA_STRING " + typeArr[i] + "  ? ");
                sqlStat2.append("AND E.ELEMENT_ID = " + elementIDArr[i] + " ");    
                preStat2 = dbConn.prepareStatement(sqlStat2.toString());
                this.setPrepareStatement(preStat2, 1, searchKeyword);
                rs2= preStat2.executeQuery();
                String submissionID = "";
                while (rs2.next()) {
                  submissionID += ((submissionID.length()>0)?",":"") + getResultSetInteger(rs2, "SUBMISSION_ID");
                }    
                submissionID = !Utility.isEmpty(submissionID) ? submissionID : "-1";
                sqlStat.append("AND C.ID in ("+submissionID+") "); 
                sqlStatCnt.append("AND C.ID in ("+submissionID+") "); 
                sqlStat2 = new StringBuffer();
              } 
            }          
          }
        }
        
        Object[] elementIDArr1 = (Object[])selectionObject[0];       
        Object[] keywordArr1 = (Object[])selectionObject[1];
        if (!Utility.isEmpty(elementIDArr1) && !"null".equals(elementIDArr1)){
          for (int i=0; i<elementIDArr1.length; i++){               
            if (!Utility.isEmpty(elementIDArr1[i].toString()) ){                
              if (!Utility.isEmpty(keywordArr1[i].toString())){
                sqlStat2.append("SELECT DISTINCT E.SUBMISSION_ID FROM FORM_DATA_ELEMENT E, FORM_DATA D ");
                sqlStat2.append("WHERE D.DATA_ELEMENT_ID = E.ID ");             
                sqlStat2.append("AND D.DATA_STRING = " +  keywordArr1[i] + " ");
                sqlStat2.append("AND E.ELEMENT_ID = " + elementIDArr1[i] + " ");    
                preStat2 = dbConn.prepareStatement(sqlStat2.toString());
                rs2= preStat2.executeQuery();
                String submissionID = "";
                while (rs2.next()) {
                  submissionID += ((submissionID.length()>0)?",":"") + getResultSetInteger(rs2, "SUBMISSION_ID");
                }    
                submissionID = !Utility.isEmpty(submissionID) ? submissionID : "-1";
                sqlStat.append("AND C.ID in ("+submissionID+") "); 
                sqlStatCnt.append("AND C.ID in ("+submissionID+") "); 
                sqlStat2 = new StringBuffer();
              }
            }         
          } 
        }
        sqlStat.append(attachedSqlStat);       
        sqlStat.append(attachedString);           
        sqlStat = this.getFormattedSQL(sqlStat.toString());

        // Form the ORDER clause for sorting.
        if (searchForm.isSortable()) {
          String sortAttribute = searchForm.getSortAttribute();
          if (sortAttribute.indexOf(".") < 0) {
            if ("TITLE".equals(sortAttribute)){
              sortAttribute = "UPDATE_DATE";
              searchForm.setSortAttribute("UPDATE_DATE");
              searchForm.setSortOrder("DESC");
            }
            sortAttribute = "C." + sortAttribute;             
          }       
          sqlStat.append("ORDER BY " + sortAttribute + " " + searchForm.getSortOrder());         
        }
        
        // Get total number of record return.
        if (isTracking) {
          sqlStatCnt.append("AND C.CREATOR_ID = '"+ sessionContainer.getUserRecordID() +"' ");
        }else{
          sqlStatCnt.append("AND C.STATUS <> '" + FormSubmission.FORM_SUBMISSION_STATU_SAVED + "' ");
          if (!Utility.isEmpty(searchSubmitter) && !"null".equals(searchSubmitter)){
            sqlStatCnt.append("AND C.CREATOR_ID = " + searchSubmitter + " ");
          }
        } 
        sqlStatCnt.append(attachedSqlStat);       
        sqlStatCnt.append(attachedString);    
                      
        preStatCnt = dbConn.prepareStatement(sqlStatCnt.toString());
        this.setPrepareStatement(preStatCnt, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStatCnt, 2, formRecordID);

        rsCnt = preStatCnt.executeQuery();
        if (rsCnt.next()) {
          totalNumOfRecord = rsCnt.getInt(1);
        }

        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }

        // Retrieve the result in row basis.
        sqlStat = this.getSelectListSQL(sqlStat, startOffset, pageSize);
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 2, formRecordID);

        rs = preStat.executeQuery();

        this.positionCursor(rs, startOffset, pageSize);

        while (rs.next() && rowLoopCnt<pageSize) {
          FormSubmission tmpFormSubmission = new FormSubmission();

          tmpFormSubmission.setFormCode(getResultSetString(rs, "FORM_CODE"));
          tmpFormSubmission.setFormVersion(getResultSetString(rs, "FORM_VERSION"));
          tmpFormSubmission.setTitle(getResultSetString(rs, "TITLE"));
          tmpFormSubmission.setID(getResultSetInteger(rs, "ID"));
          tmpFormSubmission.setTrackID(getResultSetInteger(rs, "TRACK_ID"));
          tmpFormSubmission.setFormRecordID(getResultSetInteger(rs, "FORM_RECORD_ID"));
          tmpFormSubmission.setWorkflowRecordID(getResultSetInteger(rs, "WORKFLOW_RECORD_ID"));
          tmpFormSubmission.setIp(getResultSetString(rs, "IP"));
          tmpFormSubmission.setGuestName(getResultSetString(rs, "GUEST_NAME"));
          tmpFormSubmission.setEmail(getResultSetString(rs, "EMAIL"));
          tmpFormSubmission.setContactInfo(getResultSetString(rs, "CONTACT_INFO"));
          tmpFormSubmission.setDmsParentID(getResultSetInteger(rs, "DMS_PARENT_ID"));
          tmpFormSubmission.setStatus(getResultSetString(rs, "STATUS"));
          tmpFormSubmission.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormSubmission.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormSubmission.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormSubmission.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpFormSubmission.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpFormSubmission.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpFormSubmission.setCreatorName(UserInfoFactory.getUserFullName(tmpFormSubmission.getCreatorID()));
          tmpFormSubmission.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormSubmission.getUpdaterID()));
          tmpFormSubmission.setRecordCount(totalNumOfRecord);

          // Retrive the workflow relationship.
          if (isTracking) {
            com.dcivision.workflow.dao.MtmWorkflowProgressSystemObjectDAObject mtmWfProgressSysObjDAO = new com.dcivision.workflow.dao.
              MtmWorkflowProgressSystemObjectDAObject(sessionContainer, dbConn);
            com.dcivision.workflow.dao.WorkflowRecordDAObject workflowRecordDAO = new com.dcivision.workflow.dao.WorkflowRecordDAObject(sessionContainer, dbConn);

            List tmpList = mtmWfProgressSysObjDAO.getListByBeanClassNameObjectID(tmpFormSubmission.getClass().getName(), getResultSetInteger(rs, "ID"));
            List workflowRelationshipList = new ArrayList();

            if(tmpList.size()>0){
              com.dcivision.workflow.bean.MtmWorkflowProgressSystemObject tmpObj = (com.dcivision.workflow.bean.MtmWorkflowProgressSystemObject)tmpList.get(0);
              com.dcivision.workflow.bean.WorkflowRecord wfRec = (com.dcivision.workflow.bean.WorkflowRecord)workflowRecordDAO.getObjectByTrackID(tmpObj.getTrackID());
              if (wfRec != null) {
                workflowRelationshipList.add(new Object[] {wfRec, tmpObj.getTrackID()});
              }
              tmpFormSubmission.setWorkflowRelationshipList(workflowRelationshipList);
            }
            mtmWfProgressSysObjDAO=null;
            workflowRecordDAO=null;
          }

          tmpFormSubmission.setRowNum(startOffset++);
          ++rowLoopCnt;
          result.add(tmpFormSubmission);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }
      }
    }
  }
  
  public synchronized List getFormSubmissionListByAdvanceSearchFormMonitoring(
      AbstractSearchForm searchForm,
      boolean isTracking )
      throws ApplicationException {
    String formRecordID = ((ListFormSubmissionForm)searchForm).getFormRecordID();
    PreparedStatement preStat = null;
    PreparedStatement preStat2 = null;
    PreparedStatement preStatCnt = null;
    ResultSet rs = null;
    ResultSet rs2 = null;
    ResultSet rsCnt = null;
    StringBuffer sqlStat = new StringBuffer();
    StringBuffer sqlStatCnt = new StringBuffer();   
    StringBuffer sqlStatTmp1 = new StringBuffer();
    StringBuffer sqlStatTmp2 = new StringBuffer();
    StringBuffer sqlStatCntTmp1 = new StringBuffer();
    StringBuffer sqlStatCntTmp2 = new StringBuffer();
    List result = new ArrayList();
    int totalNumOfRecord = 0;
    int rowLoopCnt = 0;
    int startOffset = TextUtility.parseInteger(searchForm.getCurStartRowNo());
    int pageSize = TextUtility.parseInteger(searchForm.getPageOffset());
    boolean isShowMyForm = !Utility.isEmpty(((ListFormSubmissionForm)searchForm).getSearchFormType()) ? true : false;
    
    ListFormSubmissionForm listFormSubmissionForm = (ListFormSubmissionForm)searchForm;
    String fromDate = listFormSubmissionForm.getFromDate();
    String toDate = TextUtility.dbDateAdder(listFormSubmissionForm.getToDate(), 1);
    String searchSubmitter = listFormSubmissionForm.getSearchSubmitter();
    String attachedStringForDatepicker = "";
    String attachedString = "";
    String attachedString2 = "";

    Map searchPanelMap = new HashMap();
    Object[] textBoxObject = new Object[3];
    Object[] datePickerObject = new Object[3];
    Object[] selectionObject = new Object[2];
    searchPanelMap = listFormSubmissionForm.getSearchPanelMap();
    textBoxObject = (Object[])searchPanelMap.get("textBoxObject");
    selectionObject = (Object[])searchPanelMap.get("selectionObject");
    datePickerObject = (Object[])searchPanelMap.get("datePickerObject");
    
    
    StringBuffer sqlStat2 = new StringBuffer();


    if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_ORACLE) {
        if (!Utility.isEmpty(fromDate) && Utility.isEmpty(toDate)) {
        attachedString2 = " AND C.UPDATE_DATE >= TO_DATE('" + fromDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      } else if (Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString2 = " AND C.UPDATE_DATE <= TO_DATE('" + toDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      } else if (!Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString2 = " AND C.UPDATE_DATE BETWEEN TO_DATE('" + fromDate + "', 'YYYY-MM-DD HH24:MI:SS') AND TO_DATE('"+  toDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      }
    } else {
        if (!Utility.isEmpty(fromDate) && Utility.isEmpty(toDate)) {
        attachedString2 = " AND C.UPDATE_DATE >= '" + fromDate + "' ";
      } else if (Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString2 = " AND C.UPDATE_DATE <= '" + toDate + "' ";
      } else if (!Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString2 = " AND C.UPDATE_DATE BETWEEN '" + fromDate + "' AND '"+  toDate + "' ";
      }
    }
    if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_ORACLE) {
      if (!Utility.isEmpty(fromDate) && Utility.isEmpty(toDate)) {
        attachedString = " AND WP.UPDATE_DATE >= TO_DATE('" + fromDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      } else if (Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND WP.UPDATE_DATE <= TO_DATE('" + toDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      } else if (!Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND WP.UPDATE_DATE BETWEEN TO_DATE('" + fromDate + "', 'YYYY-MM-DD HH24:MI:SS') AND TO_DATE('"+  toDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      }
    } else {
      if (!Utility.isEmpty(fromDate) && Utility.isEmpty(toDate)) {
        attachedString = " AND WP.UPDATE_DATE >= '" + fromDate + "' ";
      } else if (Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND WP.UPDATE_DATE <= '" + toDate + "' ";
      } else if (!Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString = " AND WP.UPDATE_DATE BETWEEN '" + fromDate + "' AND '"+  toDate + "' ";
      }
    }
    
    
    if (!Utility.isEmpty(datePickerObject) && !"null".equals(datePickerObject)){  
      Object[] elementIDArr = (Object[])datePickerObject[0];
      Object[] fromDateArr = (Object[])datePickerObject[1];
      Object[] toDateArr = (Object[])datePickerObject[2];
      if (!Utility.isEmpty(elementIDArr) && !"null".equals(elementIDArr)){
        for (int i=0; i<elementIDArr.length; i++){               
          if (!Utility.isEmpty(elementIDArr[i].toString()) ){
            if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_ORACLE) {
              if (!Utility.isEmpty(fromDateArr[i].toString()) && Utility.isEmpty(toDateArr[i].toString())) {
                attachedStringForDatepicker = " AND D.DATA_STRING >= TO_DATE('" + fromDateArr[i] + "', 'YYYY-MM-DD HH24:MI:SS') AND E.ELEMENT_ID = " + elementIDArr[i] + " ";
              } else if (Utility.isEmpty(fromDateArr[i].toString()) && !Utility.isEmpty(toDateArr[i].toString())) {
                attachedStringForDatepicker = " AND D.DATA_STRING <= TO_DATE('" + TextUtility.dbDateAdder(toDateArr[i].toString(),1) + "', 'YYYY-MM-DD HH24:MI:SS') AND E.ELEMENT_ID = " + elementIDArr[i] + " ";
              } else if (!Utility.isEmpty(fromDateArr[i].toString()) && !Utility.isEmpty(toDateArr[i].toString())) {
                attachedStringForDatepicker = " AND D.DATA_STRING BETWEEN TO_DATE('" + fromDateArr[i] + "', 'YYYY-MM-DD HH24:MI:SS') AND TO_DATE('"+  TextUtility.dbDateAdder(toDateArr[i].toString(),1) + "', 'YYYY-MM-DD HH24:MI:SS') AND E.ELEMENT_ID = " + elementIDArr[i] + " ";
              }
            } else {
              if (!Utility.isEmpty(fromDateArr[i].toString()) && Utility.isEmpty(toDateArr[i].toString())) {
                attachedStringForDatepicker = " AND D.DATA_STRING >= '" + fromDateArr[i] + "' AND E.ELEMENT_ID = " + elementIDArr[i] + " ";
              } else if (Utility.isEmpty(fromDateArr[i].toString()) && !Utility.isEmpty(toDateArr[i].toString())) {
                attachedStringForDatepicker = " AND D.DATA_STRING <= '" + TextUtility.dbDateAdder(toDateArr[i].toString(),1) + "' AND E.ELEMENT_ID = " + elementIDArr[i] + " ";
              } else if (!Utility.isEmpty(fromDateArr[i].toString()) && !Utility.isEmpty(toDateArr[i].toString())) {
                attachedStringForDatepicker = " AND D.DATA_STRING BETWEEN '" + fromDateArr[i] + "' AND '"+  TextUtility.dbDateAdder(toDateArr[i].toString(),1) + "' AND E.ELEMENT_ID = " + elementIDArr[i] + " ";
              }
            }
            if (!Utility.isEmpty(attachedStringForDatepicker)){
              sqlStat2.append("SELECT DISTINCT E.SUBMISSION_ID FROM FORM_DATA_ELEMENT E, FORM_DATA D ");
              sqlStat2.append("WHERE D.DATA_ELEMENT_ID = E.ID ");  
              sqlStat2.append(attachedStringForDatepicker);  
              try {
              preStat2 = dbConn.prepareStatement(sqlStat2.toString());
              rs2= preStat2.executeQuery();
              String submissionID = "";
              while (rs2.next()) {
                submissionID += ((submissionID.length()>0)?",":"") + getResultSetInteger(rs2, "SUBMISSION_ID");
              }    
              submissionID = !Utility.isEmpty(submissionID) ? submissionID : "-1";
              attachedStringForDatepicker = "AND C.ID in ("+submissionID+") ";             
              sqlStat2 = new StringBuffer();
              } catch (ApplicationException appEx) {
                throw appEx;
              } catch (SQLException sqle) {
                log.error(sqle, sqle);
                throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
              } catch (Exception e) {
                log.error(e, e);
                throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
              }
            }
          }
        }
      } 
    }

    synchronized(dbConn) {
      try {
        if (isTracking || isShowMyForm) {
          sqlStatTmp1.append("SELECT DISTINCT C.FORM_RECORD_ID,  C.ID, C.WORKFLOW_RECORD_ID, C.TRACK_ID, WR.WORKFLOW_CODE, WR.WORKFLOW_VERSION, WS.ID STEP_ID, WS.STEP_NAME, WP.STATUS STATUS, C.RECORD_STATUS, C.UPDATE_COUNT, MUR.CREATOR_ID CREATOR_ID, MUR.CREATE_DATE CREATE_DATE, MUR.UPDATER_ID UPDATER_ID,MUR.UPDATE_DATE UPDATE_DATE ");  
        }else{
          sqlStatTmp1.append("SELECT DISTINCT C.FORM_RECORD_ID,  C.ID, C.WORKFLOW_RECORD_ID, C.TRACK_ID, WR.WORKFLOW_CODE, WR.WORKFLOW_VERSION, WS.ID STEP_ID, WS.STEP_NAME, WP.STATUS STATUS, C.RECORD_STATUS, C.UPDATE_COUNT, WP.CREATOR_ID CREATOR_ID, C.CREATE_DATE CREATE_DATE, WP.UPDATER_ID UPDATER_ID,WP.UPDATE_DATE UPDATE_DATE ");  
        }
        sqlStatTmp1.append("FROM FORM_SUBMISSION C "); 
        sqlStatTmp1.append("INNER JOIN WORKFLOW_RECORD WR ON WR.ID = C.WORKFLOW_RECORD_ID "); 
        sqlStatTmp1.append("INNER JOIN WORKFLOW_STEP WS ON WR.ID = WS.WORKFLOW_RECORD_ID AND WS.STEP_SEQ <> '999999999' ");
        sqlStatTmp1.append("INNER JOIN WORKFLOW_PROGRESS WP ON WP.WORKFLOW_STEP_ID = WS.ID  ");
        if (isTracking || isShowMyForm){
          sqlStatTmp1.append("INNER JOIN MTM_WF_PROGRESS_USER_RECORD MUR ON MUR.WORKFLOW_PROGRESS_ID = WP.ID  ");
        }
        sqlStatTmp1.append("WHERE WS.RECORD_STATUS = WR.RECORD_STATUS AND WS.RECORD_STATUS = WP.RECORD_STATUS AND C.RECORD_STATUS = WS.RECORD_STATUS  ");
        sqlStatTmp1.append("AND C.TRACK_ID = WP.TRACK_ID ");
        sqlStatTmp1.append("AND C.RECORD_STATUS = ? AND C.FORM_RECORD_ID = ? ");
        if (isTracking || isShowMyForm) {
          sqlStatTmp1.append("AND MUR.UPDATER_ID = '"+ sessionContainer.getUserRecordID() +"' ");
        }else{
          sqlStatTmp1.append("AND WP.STATUS <> 'P' AND C.STATUS <> '" + FormSubmission.FORM_SUBMISSION_STATU_SAVED + "' ");
          if (!Utility.isEmpty(searchSubmitter) && !"null".equals(searchSubmitter)){
            sqlStatTmp1.append("AND WP.UPDATER_ID = " + searchSubmitter + " ");
          }
        }
        
        sqlStatTmp2.append("SELECT DISTINCT C.FORM_RECORD_ID, C.ID, C.WORKFLOW_RECORD_ID, C.TRACK_ID, WR.WORKFLOW_CODE, WR.WORKFLOW_VERSION, WS.ID STEP_ID, WS.STEP_NAME, C.STATUS STATUS,C.RECORD_STATUS,C.UPDATE_COUNT, C.CREATOR_ID CREATOR_ID, C.CREATE_DATE CREATE_DATE, C.UPDATER_ID UPDATER_ID,C.UPDATE_DATE UPDATE_DATE "); 
        sqlStatTmp2.append("FROM FORM_SUBMISSION C "); 
        sqlStatTmp2.append("LEFT JOIN WORKFLOW_RECORD WR ON WR.ID = C.WORKFLOW_RECORD_ID "); 
        sqlStatTmp2.append("LEFT JOIN WORKFLOW_STEP WS ON WR.ID = WS.WORKFLOW_RECORD_ID ");
        sqlStatTmp2.append("LEFT JOIN WORKFLOW_PROGRESS WP ON WP.WORKFLOW_STEP_ID = WS.ID AND WS.RECORD_STATUS = WR.RECORD_STATUS AND WS.RECORD_STATUS = WP.RECORD_STATUS ");
        sqlStatTmp2.append("WHERE C.RECORD_STATUS = ? AND C.FORM_RECORD_ID = ? AND C.WORKFLOW_RECORD_ID IS NULL ");
        
        if (isTracking || isShowMyForm) {
          sqlStatTmp2.append("AND C.CREATOR_ID = '"+ sessionContainer.getUserRecordID() +"' ");
        }else{
          sqlStatTmp2.append("AND C.STATUS <> '" + FormSubmission.FORM_SUBMISSION_STATU_SAVED + "' ");
          if (!Utility.isEmpty(searchSubmitter) && !"null".equals(searchSubmitter)){
            sqlStatTmp2.append("AND C.CREATOR_ID = " + searchSubmitter + " ");
          }
        } 
        //
        
        Object[] elementIDArr = (Object[])textBoxObject[0];
        Object[] typeArr = (Object[])textBoxObject[1];
        Object[] keywordArr = (Object[])textBoxObject[2];
        if (!Utility.isEmpty(elementIDArr) && !"null".equals(elementIDArr)){
          for (int i=0; i<elementIDArr.length; i++){               
            if (!Utility.isEmpty(elementIDArr[i].toString()) ){         
              if (!Utility.isEmpty(keywordArr[i].toString())){
                sqlStat2.append("SELECT DISTINCT E.SUBMISSION_ID FROM FORM_DATA_ELEMENT E, FORM_DATA D ");
                sqlStat2.append("WHERE D.DATA_ELEMENT_ID = E.ID ");             
                String searchKeyword = this.getFormattedKeyword(keywordArr[i].toString(), typeArr[i].toString());
                sqlStat2.append("AND D.DATA_STRING " + typeArr[i] + "  ? ");
                sqlStat2.append("AND E.ELEMENT_ID = " + elementIDArr[i] + " ");    
                preStat2 = dbConn.prepareStatement(sqlStat2.toString());
                this.setPrepareStatement(preStat2, 1, searchKeyword);
                rs2= preStat2.executeQuery();
                String submissionID = "";
                while (rs2.next()) {
                  submissionID += ((submissionID.length()>0)?",":"") + getResultSetInteger(rs2, "SUBMISSION_ID");
                }    
                submissionID = !Utility.isEmpty(submissionID) ? submissionID : "-1";
                sqlStatTmp1.append("AND C.ID in ("+submissionID+") "); 
                sqlStatTmp2.append("AND C.ID in ("+submissionID+") ");  
                sqlStat2 = new StringBuffer();
              } 
            }          
          }
        }
        
        Object[] elementIDArr1 = (Object[])selectionObject[0];       
        Object[] keywordArr1 = (Object[])selectionObject[1];
        if (!Utility.isEmpty(elementIDArr1) && !"null".equals(elementIDArr1)){
          for (int i=0; i<elementIDArr1.length; i++){               
            if (!Utility.isEmpty(elementIDArr1[i].toString()) ){                
              if (!Utility.isEmpty(keywordArr1[i].toString())){
                sqlStat2.append("SELECT DISTINCT E.SUBMISSION_ID FROM FORM_DATA_ELEMENT E, FORM_DATA D ");
                sqlStat2.append("WHERE D.DATA_ELEMENT_ID = E.ID ");             
                sqlStat2.append("AND D.DATA_STRING = " +  keywordArr1[i] + " ");
                sqlStat2.append("AND E.ELEMENT_ID = " + elementIDArr1[i] + " ");    
                preStat2 = dbConn.prepareStatement(sqlStat2.toString());
                rs2= preStat2.executeQuery();
                String submissionID = "";
                while (rs2.next()) {
                  submissionID += ((submissionID.length()>0)?",":"") + getResultSetInteger(rs2, "SUBMISSION_ID");
                }    
                submissionID = !Utility.isEmpty(submissionID) ? submissionID : "-1";
                sqlStatTmp1.append("AND C.ID in ("+submissionID+") "); 
                sqlStatTmp2.append("AND C.ID in ("+submissionID+") "); 
                sqlStat2 = new StringBuffer();
              }
            }         
          } 
        }
        sqlStatTmp1.append(attachedString);
        sqlStatTmp1.append(attachedStringForDatepicker);
        sqlStatTmp2.append(attachedString2);
        sqlStatTmp2.append(attachedStringForDatepicker);
        sqlStat.append(sqlStatTmp1);
        sqlStat.append("UNION ");
        sqlStat.append(sqlStatTmp2);
        
        sqlStat = this.getFormattedSQL(sqlStat.toString());

        // Form the ORDER clause for sorting.
        if (searchForm.isSortable()) {
          String sortAttribute = searchForm.getSortAttribute();
          if (sortAttribute.indexOf(".") < 0) {
            if ("TITLE".equals(sortAttribute)){
              sortAttribute = "UPDATE_DATE";
              searchForm.setSortAttribute("UPDATE_DATE");
              searchForm.setSortOrder("DESC");
            }      
          }       
          sqlStat.append("ORDER BY " + sortAttribute + " " + searchForm.getSortOrder());         
        }
        
        // Get total number of record return.
        sqlStatCnt = this.getSelectCountSQL(sqlStatTmp1);      
        preStatCnt = dbConn.prepareStatement(sqlStatCnt.toString());
        this.setPrepareStatement(preStatCnt, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStatCnt, 2, formRecordID);
        rsCnt = preStatCnt.executeQuery();
        if (rsCnt.next()) {
          totalNumOfRecord = rsCnt.getInt(1);
        }
        sqlStatCnt = new StringBuffer("SELECT COUNT(DISTINCT C.ID) FROM ");
        int idx = sqlStatTmp2.indexOf("FROM ");
        sqlStatCnt.append(sqlStatTmp2.substring(idx + 5));
        if (sqlStatCnt.indexOf("ORDER BY") >= 0) {
          sqlStatCnt = new StringBuffer(sqlStatCnt.substring(0, sqlStatCnt.indexOf("ORDER BY") - 1));
        }        
        preStatCnt = dbConn.prepareStatement(sqlStatCnt.toString());
        this.setPrepareStatement(preStatCnt, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStatCnt, 2, formRecordID);
        rsCnt = preStatCnt.executeQuery();
        if (rsCnt.next()) {
          totalNumOfRecord += rsCnt.getInt(1);
        }       
    
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }

        // Retrieve the result in row basis.
        if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_MSSQL){
          sqlStat = this.getSelectListMSSQLForForm(sqlStat, startOffset, pageSize);
        }else{
          sqlStat = this.getSelectListSQL(sqlStat, startOffset, pageSize);	
        }
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 2, formRecordID);
        this.setPrepareStatement(preStat, 3, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 4, formRecordID);

        rs = preStat.executeQuery();

        this.positionCursor(rs, startOffset, pageSize);

        while (rs.next() && rowLoopCnt<pageSize) {
          FormSubmission tmpFormSubmission = new FormSubmission();

          tmpFormSubmission.setID(getResultSetInteger(rs, "ID"));
          tmpFormSubmission.setTrackID(getResultSetInteger(rs, "TRACK_ID"));
          tmpFormSubmission.setFormRecordID(getResultSetInteger(rs, "FORM_RECORD_ID"));
          tmpFormSubmission.setWorkflowRecordID(getResultSetInteger(rs, "WORKFLOW_RECORD_ID"));
          tmpFormSubmission.setWorkflowCode(getResultSetString(rs, "WORKFLOW_CODE"));
          tmpFormSubmission.setWorkflowStepID(getResultSetInteger(rs, "STEP_ID"));
          tmpFormSubmission.setWorkflowStepName(getResultSetString(rs, "STEP_NAME"));         
          tmpFormSubmission.setStatus(getResultSetString(rs, "STATUS"));
          tmpFormSubmission.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormSubmission.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormSubmission.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormSubmission.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpFormSubmission.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpFormSubmission.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpFormSubmission.setCreatorName(UserInfoFactory.getUserFullName(tmpFormSubmission.getCreatorID()));
          tmpFormSubmission.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormSubmission.getUpdaterID()));
          tmpFormSubmission.setRecordCount(totalNumOfRecord);

          // Retrive the workflow relationship.
         // if (isTracking) {
            com.dcivision.workflow.dao.MtmWorkflowProgressSystemObjectDAObject mtmWfProgressSysObjDAO = new com.dcivision.workflow.dao.
              MtmWorkflowProgressSystemObjectDAObject(sessionContainer, dbConn);
            com.dcivision.workflow.dao.WorkflowRecordDAObject workflowRecordDAO = new com.dcivision.workflow.dao.WorkflowRecordDAObject(sessionContainer, dbConn);

            List tmpList = mtmWfProgressSysObjDAO.getListByBeanClassNameObjectID(tmpFormSubmission.getClass().getName(), getResultSetInteger(rs, "ID"));
            List workflowRelationshipList = new ArrayList();

            if(tmpList.size()>0){
              com.dcivision.workflow.bean.MtmWorkflowProgressSystemObject tmpObj = (com.dcivision.workflow.bean.MtmWorkflowProgressSystemObject)tmpList.get(0);
              com.dcivision.workflow.bean.WorkflowRecord wfRec = (com.dcivision.workflow.bean.WorkflowRecord)workflowRecordDAO.getObjectByTrackID(tmpObj.getTrackID());
              if (wfRec != null) {
                workflowRelationshipList.add(new Object[] {wfRec, tmpObj.getTrackID()});
              }
              tmpFormSubmission.setWorkflowRelationshipList(workflowRelationshipList);
            }
            mtmWfProgressSysObjDAO=null;
            workflowRecordDAO=null;
         // }

          tmpFormSubmission.setRowNum(startOffset++);
          ++rowLoopCnt;
          result.add(tmpFormSubmission);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }
      }
    }
  }

  /**
   * get the pending form submission list by track ID
   * @param trackID
   * @return
   * @throws ApplicationException
   */
  public synchronized List getPendingListByTrackID(Integer trackID) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.TRACK_ID, A.FORM_RECORD_ID, A.WORKFLOW_RECORD_ID, A.IP, A.GUEST_NAME, A.EMAIL, A.CONTACT_INFO, A.DMS_PARENT_ID, A.STATUS, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   FORM_SUBMISSION A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? ");
        sqlStat.append("AND  A.STATUS = ? ");
        sqlStat.append("AND  A.TRACK_ID = ? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 2, FormSubmission.FORM_SUBMISSION_STATU_PENDING);
        this.setPrepareStatement(preStat, 3, trackID);
        rs = preStat.executeQuery();
        while (rs.next()) {
          FormSubmission tmpFormSubmission = new FormSubmission();
          tmpFormSubmission.setID(getResultSetInteger(rs, "ID"));
          tmpFormSubmission.setTrackID(getResultSetInteger(rs, "TRACK_ID"));
          tmpFormSubmission.setFormRecordID(getResultSetInteger(rs, "FORM_RECORD_ID"));
          tmpFormSubmission.setWorkflowRecordID(getResultSetInteger(rs, "WORKFLOW_RECORD_ID"));
          tmpFormSubmission.setIp(getResultSetString(rs, "IP"));
          tmpFormSubmission.setGuestName(getResultSetString(rs, "GUEST_NAME"));
          tmpFormSubmission.setEmail(getResultSetString(rs, "EMAIL"));
          tmpFormSubmission.setContactInfo(getResultSetString(rs, "CONTACT_INFO"));
          tmpFormSubmission.setDmsParentID(getResultSetInteger(rs, "DMS_PARENT_ID"));
          tmpFormSubmission.setStatus(getResultSetString(rs, "STATUS"));
          tmpFormSubmission.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormSubmission.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormSubmission.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormSubmission.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpFormSubmission.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpFormSubmission.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpFormSubmission.setCreatorName(UserInfoFactory.getUserFullName(tmpFormSubmission.getCreatorID()));
          tmpFormSubmission.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormSubmission.getUpdaterID()));
          result.add(tmpFormSubmission);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }
  
  /**
   * get the has permission form submission list by trackID and workflow step ID.
   * @param trackID
   * @param workflowStepID
   * @return
   * @throws ApplicationException
   */
  public synchronized List getHasPermissionListByTrackIDWorkflowStepID(Integer trackID, Integer workflowStepID) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();

    synchronized(dbConn) {
      try {
        sqlStat.append(" SELECT A.ID, A.TRACK_ID, A.FORM_RECORD_ID, A.WORKFLOW_RECORD_ID, A.IP, A.GUEST_NAME, A.EMAIL, A.CONTACT_INFO, A.DMS_PARENT_ID, A.STATUS, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append(" FROM FORM_SUBMISSION A, MTM_WF_STEP_FORM_RECORD B ");
        
        sqlStat.append(" WHERE A.FORM_RECORD_ID = B.FORM_RECORD_ID ");
        sqlStat.append(" AND A.RECORD_STATUS = B.RECORD_STATUS ");
        sqlStat.append(" AND A.RECORD_STATUS = ? ");
        sqlStat.append(" AND B.PERMISSION <> ? ");
        sqlStat.append(" AND A.TRACK_ID = ? ");
        sqlStat.append(" AND B.WORKFLOW_STEP_ID = ? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 2, WorkflowStep.ACTION_TYPE_SUBMIT);
        this.setPrepareStatement(preStat, 3, trackID);
        this.setPrepareStatement(preStat, 4, workflowStepID);
        
        rs = preStat.executeQuery();
        while (rs.next()) {
          FormSubmission tmpFormSubmission = new FormSubmission();
          tmpFormSubmission.setID(getResultSetInteger(rs, "ID"));
          tmpFormSubmission.setTrackID(getResultSetInteger(rs, "TRACK_ID"));
          tmpFormSubmission.setFormRecordID(getResultSetInteger(rs, "FORM_RECORD_ID"));
          tmpFormSubmission.setWorkflowRecordID(getResultSetInteger(rs, "WORKFLOW_RECORD_ID"));
          tmpFormSubmission.setIp(getResultSetString(rs, "IP"));
          tmpFormSubmission.setGuestName(getResultSetString(rs, "GUEST_NAME"));
          tmpFormSubmission.setEmail(getResultSetString(rs, "EMAIL"));
          tmpFormSubmission.setContactInfo(getResultSetString(rs, "CONTACT_INFO"));
          tmpFormSubmission.setDmsParentID(getResultSetInteger(rs, "DMS_PARENT_ID"));
          tmpFormSubmission.setStatus(getResultSetString(rs, "STATUS"));
          tmpFormSubmission.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormSubmission.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormSubmission.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormSubmission.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpFormSubmission.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpFormSubmission.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpFormSubmission.setCreatorName(UserInfoFactory.getUserFullName(tmpFormSubmission.getCreatorID()));
          tmpFormSubmission.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormSubmission.getUpdaterID()));
          result.add(tmpFormSubmission);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  /**
   * get Pending And Saved Form Submission List by Track ID 
   * @param trackID
   * @return
   * @throws ApplicationException
   */
  public synchronized List getPendingSavedListByTrackID(Integer trackID) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.TRACK_ID, A.FORM_RECORD_ID, A.WORKFLOW_RECORD_ID, A.IP, A.GUEST_NAME, A.EMAIL, A.CONTACT_INFO, A.DMS_PARENT_ID, A.STATUS, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   FORM_SUBMISSION A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? ");
        sqlStat.append("AND ( A.STATUS = ? OR A.STATUS = ? ) ");
        sqlStat.append("AND  A.TRACK_ID = ? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 2, FormSubmission.FORM_SUBMISSION_STATU_PENDING);
        this.setPrepareStatement(preStat, 3, FormSubmission.FORM_SUBMISSION_STATU_SAVED);
        this.setPrepareStatement(preStat, 4, trackID);
        rs = preStat.executeQuery();
        while (rs.next()) {
          FormSubmission tmpFormSubmission = new FormSubmission();
          tmpFormSubmission.setID(getResultSetInteger(rs, "ID"));
          tmpFormSubmission.setTrackID(getResultSetInteger(rs, "TRACK_ID"));
          tmpFormSubmission.setFormRecordID(getResultSetInteger(rs, "FORM_RECORD_ID"));
          tmpFormSubmission.setWorkflowRecordID(getResultSetInteger(rs, "WORKFLOW_RECORD_ID"));
          tmpFormSubmission.setIp(getResultSetString(rs, "IP"));
          tmpFormSubmission.setGuestName(getResultSetString(rs, "GUEST_NAME"));
          tmpFormSubmission.setEmail(getResultSetString(rs, "EMAIL"));
          tmpFormSubmission.setContactInfo(getResultSetString(rs, "CONTACT_INFO"));
          tmpFormSubmission.setDmsParentID(getResultSetInteger(rs, "DMS_PARENT_ID"));
          tmpFormSubmission.setStatus(getResultSetString(rs, "STATUS"));
          tmpFormSubmission.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormSubmission.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormSubmission.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormSubmission.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpFormSubmission.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpFormSubmission.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpFormSubmission.setCreatorName(UserInfoFactory.getUserFullName(tmpFormSubmission.getCreatorID()));
          tmpFormSubmission.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormSubmission.getUpdaterID()));
          result.add(tmpFormSubmission);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }
  

    public synchronized List getListByFormRecordID(Integer formRecordID) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.TRACK_ID, A.FORM_RECORD_ID, A.WORKFLOW_RECORD_ID, A.IP, A.GUEST_NAME, A.EMAIL, A.CONTACT_INFO, A.DMS_PARENT_ID, A.STATUS, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   FORM_SUBMISSION A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? AND A. FORM_RECORD_ID = ? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 2, formRecordID);
        
        rs = preStat.executeQuery();
        while (rs.next()) {
          FormSubmission tmpFormSubmission = new FormSubmission();
          tmpFormSubmission.setID(getResultSetInteger(rs, "ID"));
          tmpFormSubmission.setTrackID(getResultSetInteger(rs, "TRACK_ID"));
          tmpFormSubmission.setFormRecordID(getResultSetInteger(rs, "FORM_RECORD_ID"));
          tmpFormSubmission.setWorkflowRecordID(getResultSetInteger(rs, "WORKFLOW_RECORD_ID"));
          tmpFormSubmission.setIp(getResultSetString(rs, "IP"));
          tmpFormSubmission.setGuestName(getResultSetString(rs, "GUEST_NAME"));
          tmpFormSubmission.setEmail(getResultSetString(rs, "EMAIL"));
          tmpFormSubmission.setContactInfo(getResultSetString(rs, "CONTACT_INFO"));
          tmpFormSubmission.setDmsParentID(getResultSetInteger(rs, "DMS_PARENT_ID"));
          tmpFormSubmission.setStatus(getResultSetString(rs, "STATUS"));
          tmpFormSubmission.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormSubmission.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormSubmission.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormSubmission.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpFormSubmission.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpFormSubmission.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpFormSubmission.setCreatorName(UserInfoFactory.getUserFullName(tmpFormSubmission.getCreatorID()));
          tmpFormSubmission.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormSubmission.getUpdaterID()));
          result.add(tmpFormSubmission);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }
  
  /**
   * get history list
   * @param searchForm
   * @return
   * @throws ApplicationException
   */
  public synchronized List getFormMonitoringHistoryList(
      AbstractSearchForm searchForm )
      throws ApplicationException {
    ListFormSubmissionForm listFormSubmissionForm = (ListFormSubmissionForm)searchForm;
    List result = new ArrayList();
    if (Utility.isEmpty(listFormSubmissionForm.getSearchFormDisplayType()) || "null".equals(listFormSubmissionForm.getSearchFormDisplayType())){
      result = this.getFormMonitoringStepFormHistoryList(searchForm);
    }else{
      result = this.getFormMonitoringWholeFormHistoryList(searchForm);
    }
    return (result);
  }
  
  /**
   * get the form monitoring history list by the search section
   * @param searchForm
   * @return
   * @throws ApplicationException
   */
  public synchronized List getFormMonitoringStepFormHistoryList(
      AbstractSearchForm searchForm)
      throws ApplicationException {
    String formRecordID = ((ListFormSubmissionForm)searchForm).getFormRecordID();
    PreparedStatement preStat = null;
    PreparedStatement preStat2 = null;
    PreparedStatement preStatCnt = null;
    ResultSet rs = null;
    ResultSet rs2 = null;
    ResultSet rsCnt = null;
    StringBuffer sqlStat = new StringBuffer();
    StringBuffer sqlStatTmp1 = new StringBuffer();
    StringBuffer sqlStatTmp2 = new StringBuffer();
    StringBuffer sqlStatCnt = new StringBuffer();
    List result = new ArrayList();
    int totalNumOfRecord = 0;
    int rowLoopCnt = 0;
    int startOffset = TextUtility.parseInteger(searchForm.getCurStartRowNo());
    int pageSize = TextUtility.parseInteger(searchForm.getPageOffset());

    ListFormSubmissionForm listFormSubmissionForm = (ListFormSubmissionForm)searchForm;
    WorkflowStepDAObject workflowStepDAO = new WorkflowStepDAObject(this.sessionContainer,this.dbConn);
    String fromDate = listFormSubmissionForm.getFromDate();
    String toDate = TextUtility.dbDateAdder(listFormSubmissionForm.getToDate(), 1);
    String attachedString = "";
    String attachedString2 = "";
    String basicSearchKeyword = listFormSubmissionForm.getBasicSearchKeyword();
    String searchSubmitter = listFormSubmissionForm.getSearchSubmitter();
    StringBuffer sqlStat2 = new StringBuffer();
    String workflowRecordID = listFormSubmissionForm.getWorkflowRecordID();
    String tmpStepIDStr = "";
    
    if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_ORACLE) {
      if (!Utility.isEmpty(fromDate) && Utility.isEmpty(toDate)) {
        attachedString2 = " AND MWPUR.UPDATE_DATE >= TO_DATE('" + fromDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      } else if (Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString2 = " AND MWPUR.UPDATE_DATE <= TO_DATE('" + toDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      } else if (!Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString2 = " AND MWPUR.UPDATE_DATE BETWEEN TO_DATE('" + fromDate + "', 'YYYY-MM-DD HH24:MI:SS') AND TO_DATE('"+  toDate + "', 'YYYY-MM-DD HH24:MI:SS') ";
      }
    } else {
      if (!Utility.isEmpty(fromDate) && Utility.isEmpty(toDate)) {
        attachedString2 = " AND MWPUR.UPDATE_DATE >= '" + fromDate + "' ";
      } else if (Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString2 = " AND MWPUR.UPDATE_DATE <= '" + toDate + "' ";
      } else if (!Utility.isEmpty(fromDate) && !Utility.isEmpty(toDate)) {
        attachedString2 = " AND MWPUR.UPDATE_DATE BETWEEN '" + fromDate + "' AND '"+  toDate + "' ";
      }
    }

    synchronized(dbConn) {
      try {
               
        //THE RECORD FROM FORM MONITOR
        sqlStatTmp1.append("SELECT DISTINCT C.FORM_RECORD_ID,  C.ID, C.WORKFLOW_RECORD_ID, C.TRACK_ID, WR.WORKFLOW_CODE, WR.WORKFLOW_VERSION, WS.ID STEP_ID, WS.STEP_NAME, FDE.WORKFLOW_PROGRESS_ID PROGRESS_ID, WP.STATUS STATUS, C.RECORD_STATUS, C.UPDATE_COUNT, FDE.CREATOR_ID CREATOR_ID, MAX(FDE.CREATE_DATE) CREATE_DATE, FDE.UPDATER_ID UPDATER_ID, C.UPDATE_DATE UPDATE_DATE, FDE.SEQ  "); 
        sqlStatTmp1.append("FROM FORM_SUBMISSION C  ");
        sqlStatTmp1.append("LEFT JOIN FORM_DATA_ELEMENT FDE ON FDE.SUBMISSION_ID = C.ID  ");
        sqlStatTmp1.append("LEFT JOIN WORKFLOW_RECORD WR ON WR.ID = C.WORKFLOW_RECORD_ID  ");
        sqlStatTmp1.append("LEFT JOIN WORKFLOW_STEP WS ON WR.ID = WS.WORKFLOW_RECORD_ID AND WS.STEP_SEQ <> '999999999'  ");
        sqlStatTmp1.append("LEFT JOIN WORKFLOW_PROGRESS WP ON WP.WORKFLOW_STEP_ID = WS.ID   ");
        sqlStatTmp1.append("WHERE C.RECORD_STATUS = ? AND C.FORM_RECORD_ID = ? ");
        

        if (!Utility.isEmpty(workflowRecordID) && !"null".equals(workflowRecordID) && !"-1".equals(workflowRecordID)){
        	sqlStatTmp1.append("AND WS.RECORD_STATUS = WR.RECORD_STATUS  ");
        	sqlStatTmp1.append("AND WS.RECORD_STATUS = WP.RECORD_STATUS AND C.RECORD_STATUS = WS.RECORD_STATUS  AND C.TRACK_ID = WP.TRACK_ID  ");
        	sqlStatTmp1.append("AND WP.STATUS <> 'P' AND C.STATUS <> 'S'  ");
        	sqlStatTmp1.append("AND FDE.WORKFLOW_PROGRESS_ID = "+listFormSubmissionForm.getProgressID()+" ");
        	sqlStatTmp1.append("AND WS.ID = "+ listFormSubmissionForm.getWorkflowStepID() +" AND FDE.SUBMIT_FLAG = '" +FormSubmission.FORM_SUBMISSION_FUNCTION+ "' ");
        }else{
          sqlStatTmp1.append("AND C.ID = " +listFormSubmissionForm.getSubmissionID()+ "  AND FDE.SUBMIT_FLAG <> '" +FormSubmission.FORM_SUBMISSION_STATU_DRAFT+ "' ");
        }
        if (!Utility.isEmpty(searchSubmitter) && !"null".equals(searchSubmitter)){
          sqlStatTmp1.append("AND FDE.CREATOR_ID = " + searchSubmitter + " ");
        }
        
        //THE RECORD FROM WF
        sqlStatTmp2.append("SELECT DISTINCT C.FORM_RECORD_ID,  C.ID, C.WORKFLOW_RECORD_ID, C.TRACK_ID, WR.WORKFLOW_CODE, WR.WORKFLOW_VERSION, ");
        sqlStatTmp2.append("WS.ID STEP_ID, WS.STEP_NAME, WP.ID PROGRESS_ID, WP.STATUS STATUS, C.RECORD_STATUS, C.UPDATE_COUNT,  ");
        sqlStatTmp2.append("MWPUR.CREATOR_ID CREATOR_ID, MWPUR.UPDATE_DATE CREATE_DATE, MWPUR.UPDATER_ID UPDATER_ID,MWPUR.UPDATE_DATE UPDATE_DATE, null SEQ   ");
        sqlStatTmp2.append("FROM FORM_SUBMISSION C  ");
        sqlStatTmp2.append("INNER JOIN WORKFLOW_RECORD WR ON WR.ID = C.WORKFLOW_RECORD_ID  ");
        sqlStatTmp2.append("INNER JOIN WORKFLOW_STEP WS ON WR.ID = WS.WORKFLOW_RECORD_ID AND WS.STEP_SEQ <> '999999999'  ");
        sqlStatTmp2.append("INNER JOIN WORKFLOW_PROGRESS WP ON WP.WORKFLOW_STEP_ID = WS.ID   ");
        sqlStatTmp2.append("INNER JOIN MTM_WF_PROGRESS_USER_RECORD MWPUR ON WP.ID = MWPUR.WORKFLOW_PROGRESS_ID  ");

        sqlStatTmp2.append("WHERE WS.RECORD_STATUS = WR.RECORD_STATUS  ");
        sqlStatTmp2.append("AND WS.RECORD_STATUS = WP.RECORD_STATUS AND C.RECORD_STATUS = WS.RECORD_STATUS  AND C.TRACK_ID = WP.TRACK_ID  ");
        sqlStatTmp2.append("AND C.RECORD_STATUS = ? AND C.FORM_RECORD_ID = ? AND WP.STATUS <> ? AND C.STATUS <> ?  ");
        sqlStatTmp2.append("AND WS.ID = ? AND WP.ID = ? ");
        if (!Utility.isEmpty(searchSubmitter) && !"null".equals(searchSubmitter)){
          sqlStatTmp2.append("AND MWPUR.CREATOR_ID = " + searchSubmitter + " ");
        }
        
        if(!Utility.isEmpty(basicSearchKeyword)){
          // For Text Box
          sqlStat2.append("SELECT DISTINCT E.SUBMISSION_ID FROM FORM_DATA_ELEMENT E ");
          sqlStat2.append("INNER JOIN FORM_DATA D ON D.DATA_ELEMENT_ID = E.ID ");
          sqlStat2.append("LEFT JOIN WORKFLOW_PROGRESS WP ON E.WORKFLOW_PROGRESS_ID = WP.ID ");
          String searchField = searchForm.getBasicSearchField();
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          sqlStat2.append("WHERE D.DATA_STRING " + searchForm.getBasicSearchType() + " ? ");
          if(searchForm.isSearchable()){
            sqlStat2.append("AND E.ELEMENT_ID = ? ");
          }
          
          preStat2 = dbConn.prepareStatement(sqlStat2.toString());
          this.setPrepareStatement(preStat2, 1, searchKeyword);  
          if(searchForm.isSearchable()){  
            this.setPrepareStatement(preStat2, 2, searchField);
          }
            
          rs2= preStat2.executeQuery();
          String submissionID = "";
          while (rs2.next()) {
            submissionID += ((submissionID.length()>0)?",":"") + getResultSetInteger(rs2, "SUBMISSION_ID");
          }
          // For Select Box, Radio Button, Check Box
          sqlStat2 = new StringBuffer();
          sqlStat2.append("SELECT DISTINCT E.SUBMISSION_ID ");
          sqlStat2.append("FROM FORM_DATA_ELEMENT E INNER JOIN FORM_DATA D ON D.DATA_ELEMENT_ID = E.ID ");
          sqlStat2.append("INNER JOIN FORM_SELECTION_FIELD F ON E.ELEMENT_ID = F.ELEMENT_ID ");
          sqlStat2.append("INNER JOIN FORM_SELECTION_FIELD_OPTION G ON G.SELECTION_FIELD_ID = F.ID ");
          sqlStat2.append("LEFT JOIN WORKFLOW_PROGRESS WP ON E.WORKFLOW_PROGRESS_ID = WP.ID ");
          sqlStat2.append("WHERE D.DATA_STRING = G.START_VALUE ");
          sqlStat2.append("AND G.LABEL " + searchForm.getBasicSearchType() + " ? ");
          if(searchForm.isSearchable()){
            sqlStat2.append("AND E.ELEMENT_ID = ? ");
          }
          
          preStat2 = dbConn.prepareStatement(sqlStat2.toString());
          this.setPrepareStatement(preStat2, 1, searchKeyword);  
          if(searchForm.isSearchable()){  
            this.setPrepareStatement(preStat2, 2, searchField);
          }
          rs2= preStat2.executeQuery();
          while (rs2.next()) {
            submissionID += ((submissionID.length()>0)?",":"") + getResultSetInteger(rs2, "SUBMISSION_ID");
          }

          if (!Utility.isEmpty(submissionID)) {
            sqlStatTmp1.append("           AND C.ID IN ("+submissionID+") ");
            sqlStatTmp2.append("           AND C.ID IN ("+submissionID+") ");
          }else{
            throw new ApplicationException(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR);
          }
          //}
          try { rs2.close(); } catch (Exception ignore) {} finally { rs2 = null; }
          try { preStat2.close(); } catch (Exception ignore) {} finally { preStat2 = null; }
        }


//        sqlStatTmp1.append(attachedString);
        if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_ORACLE) {
          if (!Utility.isEmpty(fromDate)) {
            sqlStatTmp1.append(" AND FDE.CREATE_DATE >= to_date('" + fromDate + "', 'YYYY-MM-DD HH24:MI:SS') ");
          }
          if (!Utility.isEmpty(toDate)) {
            sqlStatTmp1.append(" AND FDE.CREATE_DATE <= to_date('" + toDate + "', 'YYYY-MM-DD HH24:MI:SS') ");
          }
		  sqlStatTmp1.append("GROUP BY C.FORM_RECORD_ID,  C.ID, C.WORKFLOW_RECORD_ID, C.TRACK_ID, WR.WORKFLOW_CODE, WR.WORKFLOW_VERSION, WS.ID, WS.STEP_NAME, FDE.WORKFLOW_PROGRESS_ID, WP.STATUS, C.RECORD_STATUS, C.UPDATE_COUNT, FDE.CREATOR_ID, FDE.UPDATER_ID, C.UPDATE_DATE, FDE.SEQ ");         

        } else { 
          if (!Utility.isEmpty(fromDate)) {
            sqlStatTmp1.append(" AND FDE.CREATE_DATE >= '" + fromDate + "' ");
          }
          if (!Utility.isEmpty(toDate)) {
            sqlStatTmp1.append(" AND FDE.CREATE_DATE <= '" +  toDate + "' ");
          }
		  if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_MSSQL) {
			sqlStatTmp1.append("GROUP BY C.FORM_RECORD_ID,  C.ID, C.WORKFLOW_RECORD_ID, C.TRACK_ID, WR.WORKFLOW_CODE, WR.WORKFLOW_VERSION, WS.ID, WS.STEP_NAME, FDE.WORKFLOW_PROGRESS_ID, WP.STATUS, C.RECORD_STATUS, C.UPDATE_COUNT, FDE.CREATOR_ID, FDE.UPDATER_ID, C.UPDATE_DATE, FDE.SEQ ");                     
		  }
          if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_MYSQL) {
            sqlStatTmp1.append(" GROUP BY FDE.SEQ ");
          }
        }
               
        sqlStatTmp2.append(attachedString2);
        sqlStat.append(sqlStatTmp1);
        sqlStat.append("UNION ");
        sqlStat.append(sqlStatTmp2);
        sqlStat = this.getFormattedSQL(sqlStat.toString());

        // Form the ORDER clause for sorting.
        if (searchForm.isSortable()) {
          String sortAttribute = searchForm.getSortAttribute();
          if (sortAttribute.indexOf(".") < 0) {
            if ("TITLE".equals(sortAttribute)){
              sortAttribute = "CREATE_DATE";
              searchForm.setSortAttribute("CREATE_DATE");
              searchForm.setSortOrder("DESC");
            }
          }
          sqlStat.append("ORDER BY " + sortAttribute + " " + searchForm.getSortOrder());
        }
  
        // Get total number of record return.
        sqlStatCnt = new StringBuffer("SELECT COUNT(DISTINCT FDE.SEQ) FROM ");
        int idx = sqlStatTmp1.indexOf("FROM ");
        sqlStatCnt.append(sqlStatTmp1.substring(idx + 5));
        if (sqlStatCnt.indexOf("GROUP BY") >= 0) {
          sqlStatCnt = new StringBuffer(sqlStatCnt.substring(0, sqlStatCnt.indexOf("GROUP BY") - 1));
        }           
        preStatCnt = dbConn.prepareStatement(sqlStatCnt.toString());
        this.setPrepareStatement(preStatCnt, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStatCnt, 2, formRecordID);        
        rsCnt = preStatCnt.executeQuery();
        while (rsCnt.next()) {
          totalNumOfRecord += rsCnt.getInt(1);
        }
        
        sqlStatCnt = new StringBuffer("SELECT COUNT(DISTINCT MWPUR.ID) FROM ");
        idx = sqlStatTmp2.indexOf("FROM ");
        sqlStatCnt.append(sqlStatTmp2.substring(idx + 5));
        if (sqlStatCnt.indexOf("GROUP BY") >= 0) {
          sqlStatCnt = new StringBuffer(sqlStatCnt.substring(0, sqlStatCnt.indexOf("GROUP BY") - 1));
        }        
        preStatCnt = dbConn.prepareStatement(sqlStatCnt.toString());
        this.setPrepareStatement(preStatCnt, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStatCnt, 2, formRecordID);
        this.setPrepareStatement(preStatCnt, 3, FormSubmission.FORM_SUBMISSION_STATU_PENDING);
        this.setPrepareStatement(preStatCnt, 4, FormSubmission.FORM_SUBMISSION_STATU_SAVED);
        this.setPrepareStatement(preStatCnt, 5, listFormSubmissionForm.getWorkflowStepID());
        this.setPrepareStatement(preStatCnt, 6, listFormSubmissionForm.getProgressID());
        
        rsCnt = preStatCnt.executeQuery();
        while (rsCnt.next()) {
          totalNumOfRecord += rsCnt.getInt(1);
        }
        
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }

        // Retrieve the result in row basis.
        if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_MSSQL){
          sqlStat = this.getSelectListMSSQLForForm(sqlStat, startOffset, pageSize);
        }else{
          sqlStat = this.getSelectListSQL(sqlStat, startOffset, pageSize);	
        }  
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 2, formRecordID);     
        this.setPrepareStatement(preStat, 3, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 4, formRecordID);
        this.setPrepareStatement(preStat, 5, FormSubmission.FORM_SUBMISSION_STATU_PENDING);
        this.setPrepareStatement(preStat, 6, FormSubmission.FORM_SUBMISSION_STATU_SAVED);
        this.setPrepareStatement(preStat, 7, listFormSubmissionForm.getWorkflowStepID());
        this.setPrepareStatement(preStat, 8, listFormSubmissionForm.getProgressID());
                
        rs = preStat.executeQuery();

        this.positionCursor(rs, startOffset, pageSize);

        while (rs.next() && rowLoopCnt<pageSize) {
          FormSubmission tmpFormSubmission = new FormSubmission();

          tmpFormSubmission.setID(getResultSetInteger(rs, "ID"));
          tmpFormSubmission.setTrackID(getResultSetInteger(rs, "TRACK_ID"));
          tmpFormSubmission.setFormRecordID(getResultSetInteger(rs, "FORM_RECORD_ID"));
          tmpFormSubmission.setWorkflowRecordID(getResultSetInteger(rs, "WORKFLOW_RECORD_ID"));
          tmpFormSubmission.setWorkflowCode(getResultSetString(rs, "WORKFLOW_CODE"));
          tmpFormSubmission.setWorkflowStepID(getResultSetInteger(rs, "STEP_ID"));
          tmpFormSubmission.setWorkflowStepName(getResultSetString(rs, "STEP_NAME"));    
          tmpFormSubmission.setProgressID(getResultSetInteger(rs, "PROGRESS_ID"));
          tmpFormSubmission.setSeq(getResultSetInteger(rs, "SEQ"));
          tmpFormSubmission.setStatus(getResultSetString(rs, "STATUS"));
          tmpFormSubmission.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormSubmission.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormSubmission.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormSubmission.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpFormSubmission.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpFormSubmission.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpFormSubmission.setCreatorName(UserInfoFactory.getUserFullName(tmpFormSubmission.getCreatorID()));
          tmpFormSubmission.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormSubmission.getUpdaterID()));
          tmpFormSubmission.setRecordCount(totalNumOfRecord);
         
          tmpFormSubmission.setRowNum(startOffset++);
          ++rowLoopCnt;
          result.add(tmpFormSubmission);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }
      }
    }
  }
  
  /**
   * get the form monitoring history list by the search section
   * @param searchForm
   * @return
   * @throws ApplicationException
   */
  public synchronized List getFormMonitoringWholeFormHistoryList(
      AbstractSearchForm searchForm)
      throws ApplicationException {
    String formRecordID = ((ListFormSubmissionForm)searchForm).getFormRecordID();
    PreparedStatement preStat = null;
    PreparedStatement preStat2 = null;
    PreparedStatement preStatCnt = null;
    ResultSet rs = null;
    ResultSet rs2 = null;
    ResultSet rsCnt = null;
    StringBuffer sqlStat = new StringBuffer();
    StringBuffer sqlStatCnt = new StringBuffer("SELECT COUNT(DISTINCT FDE.SEQ) FROM ");
    List result = new ArrayList();
    int totalNumOfRecord = 0;
    int rowLoopCnt = 0;
    int startOffset = TextUtility.parseInteger(searchForm.getCurStartRowNo());
    int pageSize = TextUtility.parseInteger(searchForm.getPageOffset());

    ListFormSubmissionForm listFormSubmissionForm = (ListFormSubmissionForm)searchForm;
    WorkflowStepDAObject workflowStepDAO = new WorkflowStepDAObject(this.sessionContainer,this.dbConn);
    String fromDate = listFormSubmissionForm.getFromDate();
    String toDate = TextUtility.dbDateAdder(listFormSubmissionForm.getToDate(), 1);
    String basicSearchKeyword = listFormSubmissionForm.getBasicSearchKeyword();
    String searchSubmitter = listFormSubmissionForm.getSearchSubmitter();
    StringBuffer sqlStat2 = new StringBuffer();
    String workflowRecordID = listFormSubmissionForm.getWorkflowRecordID();
    String tmpStepIDStr = "";
 
    synchronized(dbConn) {
      try {
               
        //THE RECORD FROM FORM MONITOR
        sqlStat.append("SELECT DISTINCT C.ID, C.TRACK_ID, C.FORM_RECORD_ID, C.WORKFLOW_RECORD_ID, WR.WORKFLOW_CODE, WP.WORKFLOW_STEP_ID, C.IP,C.GUEST_NAME,C.EMAIL,C.CONTACT_INFO, C.DMS_PARENT_ID, C.STATUS,C.RECORD_STATUS,C.UPDATE_COUNT, FDE.CREATOR_ID, MAX(FDE.CREATE_DATE) CREATE_DATE, FDE.SEQ ");
        sqlStat.append("FROM FORM_SUBMISSION C ");
        sqlStat.append("LEFT JOIN WORKFLOW_RECORD WR ON WR.ID = C.WORKFLOW_RECORD_ID ");
        sqlStat.append("LEFT JOIN FORM_DATA_ELEMENT FDE ON FDE.SUBMISSION_ID = C.ID  ");
        sqlStat.append("LEFT JOIN WORKFLOW_PROGRESS WP ON WP.ID = FDE.WORKFLOW_PROGRESS_ID  ");
        sqlStat.append("WHERE (FDE.SUBMIT_FLAG <> ? ) "); 
        sqlStat.append("AND C.RECORD_STATUS = ? AND C.FORM_RECORD_ID = ? ");
        sqlStat.append("AND C.ID = " + listFormSubmissionForm.getSubmissionID()+ " ");
                
        sqlStat.append("AND C.STATUS <> '" + FormSubmission.FORM_SUBMISSION_STATU_SAVED + "' ");
        if (!Utility.isEmpty(searchSubmitter) && !"null".equals(searchSubmitter)){
        	sqlStat.append("AND C.CREATOR_ID = " + searchSubmitter + " ");
        }
          
        if(!Utility.isEmpty(basicSearchKeyword)){
          // For Text Box
          sqlStat2.append("SELECT DISTINCT E.SUBMISSION_ID FROM FORM_DATA_ELEMENT E ");
          sqlStat2.append("INNER JOIN FORM_DATA D ON D.DATA_ELEMENT_ID = E.ID ");
          sqlStat2.append("LEFT JOIN WORKFLOW_PROGRESS WP ON E.WORKFLOW_PROGRESS_ID = WP.ID ");
          String searchField = searchForm.getBasicSearchField();
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          sqlStat2.append("WHERE D.DATA_STRING " + searchForm.getBasicSearchType() + " ? ");
          if(searchForm.isSearchable()){
            sqlStat2.append("AND E.ELEMENT_ID = ? ");
          }
          
          preStat2 = dbConn.prepareStatement(sqlStat2.toString());
          this.setPrepareStatement(preStat2, 1, searchKeyword);  
          if(searchForm.isSearchable()){  
            this.setPrepareStatement(preStat2, 2, searchField);
          }
            
          rs2= preStat2.executeQuery();
          String submissionID = "";
          while (rs2.next()) {
            submissionID += ((submissionID.length()>0)?",":"") + getResultSetInteger(rs2, "SUBMISSION_ID");
          }
          // For Select Box, Radio Button, Check Box
          sqlStat2 = new StringBuffer();
          sqlStat2.append("SELECT DISTINCT E.SUBMISSION_ID ");
          sqlStat2.append("FROM FORM_DATA_ELEMENT E INNER JOIN FORM_DATA D ON D.DATA_ELEMENT_ID = E.ID ");
          sqlStat2.append("INNER JOIN FORM_SELECTION_FIELD F ON E.ELEMENT_ID = F.ELEMENT_ID ");
          sqlStat2.append("INNER JOIN FORM_SELECTION_FIELD_OPTION G ON G.SELECTION_FIELD_ID = F.ID ");
          sqlStat2.append("LEFT JOIN WORKFLOW_PROGRESS WP ON E.WORKFLOW_PROGRESS_ID = WP.ID ");
          sqlStat2.append("WHERE D.DATA_STRING = G.START_VALUE ");
          sqlStat2.append("AND G.LABEL " + searchForm.getBasicSearchType() + " ? ");
          if(searchForm.isSearchable()){
            sqlStat2.append("AND E.ELEMENT_ID = ? ");
          }
          
          preStat2 = dbConn.prepareStatement(sqlStat2.toString());
          this.setPrepareStatement(preStat2, 1, searchKeyword);  
          if(searchForm.isSearchable()){  
            this.setPrepareStatement(preStat2, 2, searchField);
          }
          rs2= preStat2.executeQuery();
          while (rs2.next()) {
            submissionID += ((submissionID.length()>0)?",":"") + getResultSetInteger(rs2, "SUBMISSION_ID");
          }

          if (!Utility.isEmpty(submissionID)) {
            sqlStat.append("           AND C.ID IN ("+submissionID+") ");
            sqlStat.append("           AND C.ID IN ("+submissionID+") ");
          }else{
            throw new ApplicationException(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR);
          }
          //}
          try { rs2.close(); } catch (Exception ignore) {} finally { rs2 = null; }
          try { preStat2.close(); } catch (Exception ignore) {} finally { preStat2 = null; }
        }
        
//        sqlStat.append(attachedString);
        if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_ORACLE) {
          if (!Utility.isEmpty(fromDate)) {
            sqlStat.append(" AND FDE.CREATE_DATE >= to_date('" + fromDate + "', 'YYYY-MM-DD HH24:MI:SS') ");
          }
          if (!Utility.isEmpty(toDate)) {
            sqlStat.append(" AND FDE.CREATE_DATE <= to_date('" + toDate + "', 'YYYY-MM-DD HH24:MI:SS') ");
          }
		  sqlStat.append("GROUP BY C.ID, C.TRACK_ID, C.FORM_RECORD_ID, C.WORKFLOW_RECORD_ID, WR.WORKFLOW_CODE, WP.WORKFLOW_STEP_ID, C.IP,C.GUEST_NAME,C.EMAIL,C.CONTACT_INFO, C.DMS_PARENT_ID, C.STATUS,C.RECORD_STATUS,C.UPDATE_COUNT, FDE.CREATOR_ID, FDE.SEQ ");         

        } else { 
         
          if (!Utility.isEmpty(fromDate)) {
            sqlStat.append(" AND FDE.CREATE_DATE >= '" + fromDate + "' ");
          }
          if (!Utility.isEmpty(toDate)) {
            sqlStat.append(" AND FDE.CREATE_DATE <= '" +  toDate + "' ");
          }
		  if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_MSSQL) {
			sqlStat.append("GROUP BY C.ID, C.TRACK_ID, C.FORM_RECORD_ID, C.WORKFLOW_RECORD_ID, WR.WORKFLOW_CODE, WP.WORKFLOW_STEP_ID, C.IP,C.GUEST_NAME,C.EMAIL,C.CONTACT_INFO, C.DMS_PARENT_ID, C.STATUS,C.RECORD_STATUS,C.UPDATE_COUNT, FDE.CREATOR_ID, FDE.SEQ ");         
		  }
          if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_MYSQL) {
            sqlStat.append("GROUP BY FDE.SEQ ");
          }
        }
        
        sqlStat = this.getFormattedSQL(sqlStat.toString());

        // Form the ORDER clause for sorting.
        if (searchForm.isSortable()) {
          String sortAttribute = searchForm.getSortAttribute();
          if (sortAttribute.indexOf(".") < 0) {
            if ("TITLE".equals(sortAttribute)){
              sortAttribute = "CREATE_DATE";
              searchForm.setSortAttribute("CREATE_DATE");
              searchForm.setSortOrder("DESC");
            }
            if ("WORKFLOW_CODE".equals(sortAttribute)){
              sortAttribute = "WR." + sortAttribute;
            }else if ("CREATOR_ID".equals(sortAttribute)){
              sortAttribute = "FDE." + sortAttribute;
            }else{
              sortAttribute = "C." + sortAttribute;
            }
          }
          sqlStat.append("ORDER BY " + sortAttribute + " " + searchForm.getSortOrder());
        }
  
        // Get total number of record return.
        int idx = sqlStat.indexOf("FROM ");
        sqlStatCnt.append(sqlStat.substring(idx + 5));
        if (sqlStatCnt.indexOf("ORDER BY") >= 0) {
          sqlStatCnt = new StringBuffer(sqlStatCnt.substring(0, sqlStatCnt.indexOf("ORDER BY") - 1));
        }                  
        preStatCnt = dbConn.prepareStatement(sqlStatCnt.toString());
        this.setPrepareStatement(preStatCnt, 1, FormSubmission.FORM_SUBMISSION_STATU_DRAFT);
        this.setPrepareStatement(preStatCnt, 2, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStatCnt, 3, formRecordID);
        
        rsCnt = preStatCnt.executeQuery();
        while (rsCnt.next()) {
          totalNumOfRecord += rsCnt.getInt(1);
        }
       
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }

        // Retrieve the result in row basis.
        sqlStat = this.getSelectListSQL(sqlStat, startOffset, pageSize);
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, FormSubmission.FORM_SUBMISSION_STATU_DRAFT);
        this.setPrepareStatement(preStat, 2, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 3, formRecordID);     
        
                
        rs = preStat.executeQuery();

        this.positionCursor(rs, startOffset, pageSize);

        while (rs.next() && rowLoopCnt<pageSize) {
          FormSubmission tmpFormSubmission = new FormSubmission();

          tmpFormSubmission.setID(getResultSetInteger(rs, "ID"));
          tmpFormSubmission.setTrackID(getResultSetInteger(rs, "TRACK_ID"));
          tmpFormSubmission.setFormRecordID(getResultSetInteger(rs, "FORM_RECORD_ID"));
          tmpFormSubmission.setWorkflowRecordID(getResultSetInteger(rs, "WORKFLOW_RECORD_ID"));
          tmpFormSubmission.setWorkflowCode(getResultSetString(rs, "WORKFLOW_CODE"));         
          tmpFormSubmission.setWorkflowStepID(getResultSetInteger(rs, "WORKFLOW_STEP_ID"));
          tmpFormSubmission.setSeq(getResultSetInteger(rs, "SEQ"));
          tmpFormSubmission.setStatus(getResultSetString(rs, "STATUS"));
          tmpFormSubmission.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormSubmission.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormSubmission.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormSubmission.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));          
          tmpFormSubmission.setCreatorName(UserInfoFactory.getUserFullName(tmpFormSubmission.getCreatorID()));
          tmpFormSubmission.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormSubmission.getUpdaterID()));
          tmpFormSubmission.setRecordCount(totalNumOfRecord);

          tmpFormSubmission.setRowNum(startOffset++);
          ++rowLoopCnt;
          result.add(tmpFormSubmission);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }
      }
    }
  }
  
  /**
   * get the form audit trail list.
   * @param searchForm
   * @return
   * @throws ApplicationException
   */
  public synchronized List getFormAuditTrailList(
      AbstractSearchForm searchForm)
      throws ApplicationException {
    ListFormSubmissionForm listFormSubmissionForm = (ListFormSubmissionForm)searchForm;
    List result = new ArrayList();
    if (Utility.isEmpty(listFormSubmissionForm.getSearchFormDisplayType()) || "null".equals(listFormSubmissionForm.getSearchFormDisplayType())){
      result = this.getFormAuditTrailStepList(searchForm);
    }else{
      result = this.getFormAuditTrailWholeList(searchForm);
    }
    return (result);
  }
  
  public synchronized List getFormAuditTrailStepList(
      AbstractSearchForm searchForm)
      throws ApplicationException {
    String formRecordID = ((ListFormSubmissionForm)searchForm).getFormRecordID();
    PreparedStatement preStat = null;
    PreparedStatement preStat2 = null;
    PreparedStatement preStatCnt = null;
    ResultSet rs = null;
    ResultSet rs2 = null;
    ResultSet rsCnt = null;
    StringBuffer sqlStat = new StringBuffer();
    StringBuffer sqlStatTmp1 = new StringBuffer();
    StringBuffer sqlStatTmp2 = new StringBuffer();
    StringBuffer sqlStatCnt = new StringBuffer();
    List result = new ArrayList();
    int totalNumOfRecord = 0;
    int rowLoopCnt = 0;
    int startOffset = TextUtility.parseInteger(searchForm.getCurStartRowNo());
    int pageSize = TextUtility.parseInteger(searchForm.getPageOffset());
    
    ListFormSubmissionForm listFormSubmissionForm = (ListFormSubmissionForm)searchForm;
    WorkflowStepDAObject workflowStepDAO = new WorkflowStepDAObject(this.sessionContainer,this.dbConn);
    
    String fromDate = listFormSubmissionForm.getFromDate();
    String toDate = TextUtility.dbDateAdder(listFormSubmissionForm.getToDate(), 1);
    String attachedString = "";
    String attachedString2 = "";
    String basicSearchKeyword = listFormSubmissionForm.getBasicSearchKeyword();
    String searchSubmitter = listFormSubmissionForm.getSearchSubmitter();
    StringBuffer sqlStat2 = new StringBuffer();
    String workflowRecordID = listFormSubmissionForm.getWorkflowRecordID();
    String tmpStepIDStr = "";
  

    synchronized(dbConn) {
      try {
               
        //THE RECORD FROM FORM MONITOR
        sqlStatTmp1.append("SELECT DISTINCT C.FORM_RECORD_ID,  C.ID, C.WORKFLOW_RECORD_ID, C.TRACK_ID, WR.WORKFLOW_CODE, WR.WORKFLOW_VERSION, WS.ID STEP_ID, WS.STEP_NAME, FDE.WORKFLOW_PROGRESS_ID PROGRESS_ID, WP.STATUS STATUS, C.RECORD_STATUS, C.UPDATE_COUNT, FDE.CREATOR_ID CREATOR_ID, MAX(FDE.CREATE_DATE) CREATE_DATE, FDE.UPDATER_ID UPDATER_ID, C.UPDATE_DATE UPDATE_DATE, FDE.SEQ  "); 
        sqlStatTmp1.append("FROM FORM_SUBMISSION C  ");
        sqlStatTmp1.append("LEFT JOIN FORM_DATA_ELEMENT FDE ON FDE.SUBMISSION_ID = C.ID  ");
        sqlStatTmp1.append("LEFT JOIN WORKFLOW_RECORD WR ON WR.ID = C.WORKFLOW_RECORD_ID  ");
        sqlStatTmp1.append("LEFT JOIN WORKFLOW_STEP WS ON WR.ID = WS.WORKFLOW_RECORD_ID AND WS.STEP_SEQ <> '999999999'  ");
        sqlStatTmp1.append("LEFT JOIN WORKFLOW_PROGRESS WP ON WP.WORKFLOW_STEP_ID = WS.ID   ");
        sqlStatTmp1.append("WHERE C.RECORD_STATUS = ? AND C.FORM_RECORD_ID = ? ");
        

        if (!Utility.isEmpty(workflowRecordID) && !"null".equals(workflowRecordID) && !"-1".equals(workflowRecordID)){
          sqlStatTmp1.append("AND WS.RECORD_STATUS = WR.RECORD_STATUS  ");
          sqlStatTmp1.append("AND WS.RECORD_STATUS = WP.RECORD_STATUS AND C.RECORD_STATUS = WS.RECORD_STATUS  AND C.TRACK_ID = WP.TRACK_ID  ");
          sqlStatTmp1.append("AND WP.STATUS <> 'P' AND C.STATUS <> 'S'  ");
          sqlStatTmp1.append("AND FDE.WORKFLOW_PROGRESS_ID = "+listFormSubmissionForm.getProgressID()+" ");
          sqlStatTmp1.append("AND WS.ID = "+ listFormSubmissionForm.getWorkflowStepID() +" AND FDE.SUBMIT_FLAG = '" +FormSubmission.FORM_SUBMISSION_FUNCTION+ "' ");
        }else{
          sqlStatTmp1.append("AND C.ID = " +listFormSubmissionForm.getSubmissionID()+ "  AND FDE.SUBMIT_FLAG <> '" +FormSubmission.FORM_SUBMISSION_STATU_DRAFT+ "' ");
        }
        if (!Utility.isEmpty(searchSubmitter) && !"null".equals(searchSubmitter)){
          sqlStatTmp1.append("AND FDE.CREATOR_ID = " + searchSubmitter + " ");
        }
        
        //THE RECORD FROM WF
        sqlStatTmp2.append("SELECT DISTINCT C.FORM_RECORD_ID,  C.ID, C.WORKFLOW_RECORD_ID, C.TRACK_ID, WR.WORKFLOW_CODE, WR.WORKFLOW_VERSION, ");
        sqlStatTmp2.append("WS.ID STEP_ID, WS.STEP_NAME, WP.ID PROGRESS_ID, WP.STATUS STATUS, C.RECORD_STATUS, C.UPDATE_COUNT,  ");
        sqlStatTmp2.append("MWPUR.CREATOR_ID CREATOR_ID, MAX(FDE.CREATE_DATE) CREATE_DATE, MWPUR.UPDATER_ID UPDATER_ID, C.UPDATE_DATE UPDATE_DATE, FDE.SEQ   ");
        sqlStatTmp2.append("FROM FORM_SUBMISSION C  "); 
        
        sqlStatTmp2.append("INNER JOIN WORKFLOW_RECORD WR ON WR.ID = C.WORKFLOW_RECORD_ID  ");
        sqlStatTmp2.append("INNER JOIN WORKFLOW_STEP WS ON WR.ID = WS.WORKFLOW_RECORD_ID AND WS.STEP_SEQ <> '999999999'  ");
        sqlStatTmp2.append("INNER JOIN WORKFLOW_PROGRESS WP ON WP.WORKFLOW_STEP_ID = WS.ID   ");
        sqlStatTmp2.append("INNER JOIN MTM_WF_PROGRESS_USER_RECORD MWPUR ON WP.ID = MWPUR.WORKFLOW_PROGRESS_ID  ");
        sqlStatTmp2.append("INNER JOIN FORM_DATA_ELEMENT FDE ON C.ID = FDE.SUBMISSION_ID AND FDE.WORKFLOW_PROGRESS_ID = WP.ID ");
        sqlStatTmp2.append("WHERE WS.RECORD_STATUS = WR.RECORD_STATUS  ");
        sqlStatTmp2.append("AND WS.RECORD_STATUS = WP.RECORD_STATUS AND C.RECORD_STATUS = WS.RECORD_STATUS  AND C.TRACK_ID = WP.TRACK_ID  ");
        sqlStatTmp2.append("AND C.RECORD_STATUS = ? AND C.FORM_RECORD_ID = ? AND WP.STATUS <> ? AND C.STATUS <> ?  ");
        sqlStatTmp2.append("AND WS.ID = ? AND WP.ID = ? ");
        sqlStatTmp2.append("AND FDE.SUBMIT_FLAG = ? ");
        if (!Utility.isEmpty(searchSubmitter) && !"null".equals(searchSubmitter)){
          sqlStatTmp1.append("AND MWPUR.CREATOR_ID = " + searchSubmitter + " ");
        }
        
        if(!Utility.isEmpty(basicSearchKeyword)){
          // For Text Box
          sqlStat2.append("SELECT DISTINCT E.SUBMISSION_ID FROM FORM_DATA_ELEMENT E ");
          sqlStat2.append("INNER JOIN FORM_DATA D ON D.DATA_ELEMENT_ID = E.ID ");
          sqlStat2.append("LEFT JOIN WORKFLOW_PROGRESS WP ON E.WORKFLOW_PROGRESS_ID = WP.ID ");
          String searchField = searchForm.getBasicSearchField();
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          sqlStat2.append("WHERE D.DATA_STRING " + searchForm.getBasicSearchType() + " ? ");
          if(searchForm.isSearchable()){
            sqlStat2.append("AND E.ELEMENT_ID = ? ");
          }
          
          preStat2 = dbConn.prepareStatement(sqlStat2.toString());
          this.setPrepareStatement(preStat2, 1, searchKeyword);  
          if(searchForm.isSearchable()){  
            this.setPrepareStatement(preStat2, 2, searchField);
          }
            
          rs2= preStat2.executeQuery();
          String submissionID = "";
          while (rs2.next()) {
            submissionID += ((submissionID.length()>0)?",":"") + getResultSetInteger(rs2, "SUBMISSION_ID");
          }
          // For Select Box, Radio Button, Check Box
          sqlStat2 = new StringBuffer();
          sqlStat2.append("SELECT DISTINCT E.SUBMISSION_ID ");
          sqlStat2.append("FROM FORM_DATA_ELEMENT E INNER JOIN FORM_DATA D ON D.DATA_ELEMENT_ID = E.ID ");
          sqlStat2.append("INNER JOIN FORM_SELECTION_FIELD F ON E.ELEMENT_ID = F.ELEMENT_ID ");
          sqlStat2.append("INNER JOIN FORM_SELECTION_FIELD_OPTION G ON G.SELECTION_FIELD_ID = F.ID ");
          sqlStat2.append("LEFT JOIN WORKFLOW_PROGRESS WP ON E.WORKFLOW_PROGRESS_ID = WP.ID ");
          sqlStat2.append("WHERE D.DATA_STRING = G.START_VALUE ");
          sqlStat2.append("AND G.LABEL " + searchForm.getBasicSearchType() + " ? ");
          if(searchForm.isSearchable()){
            sqlStat2.append("AND E.ELEMENT_ID = ? ");
          }
          
          preStat2 = dbConn.prepareStatement(sqlStat2.toString());
          this.setPrepareStatement(preStat2, 1, searchKeyword);  
          if(searchForm.isSearchable()){  
            this.setPrepareStatement(preStat2, 2, searchField);
          }
          rs2= preStat2.executeQuery();
          while (rs2.next()) {
            submissionID += ((submissionID.length()>0)?",":"") + getResultSetInteger(rs2, "SUBMISSION_ID");
          }

          if (!Utility.isEmpty(submissionID)) {
            sqlStatTmp1.append("           AND C.ID IN ("+submissionID+") ");
            sqlStatTmp2.append("           AND C.ID IN ("+submissionID+") ");
          }else{
            throw new ApplicationException(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR);
          }
          //}
          try { rs2.close(); } catch (Exception ignore) {} finally { rs2 = null; }
          try { preStat2.close(); } catch (Exception ignore) {} finally { preStat2 = null; }
        }
 
        if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_ORACLE) {
          if (!Utility.isEmpty(fromDate)) {
            sqlStatTmp1.append(" AND FDE.CREATE_DATE >= to_date('" + fromDate + "', 'YYYY-MM-DD HH24:MI:SS') ");
          }
          if (!Utility.isEmpty(toDate)) {
            sqlStatTmp1.append(" AND FDE.CREATE_DATE <= to_date('" + toDate + "', 'YYYY-MM-DD HH24:MI:SS') ");
          }
		  sqlStatTmp1.append(" GROUP BY C.FORM_RECORD_ID,  C.ID, C.WORKFLOW_RECORD_ID, C.TRACK_ID, WR.WORKFLOW_CODE, WR.WORKFLOW_VERSION, WS.ID, WS.STEP_NAME, FDE.WORKFLOW_PROGRESS_ID, WP.STATUS, C.RECORD_STATUS, C.UPDATE_COUNT, FDE.CREATOR_ID, FDE.UPDATER_ID, C.UPDATE_DATE, FDE.SEQ ") ;        

        } else {           
          if (!Utility.isEmpty(fromDate)) {
            sqlStatTmp1.append(" AND FDE.CREATE_DATE >= '" + fromDate + "' ");
          }
          if (!Utility.isEmpty(toDate)) {
            sqlStatTmp1.append(" AND FDE.CREATE_DATE <= '" +  toDate + "' ");
          }
		  if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_MSSQL) {
			sqlStatTmp1.append(" GROUP BY C.FORM_RECORD_ID,  C.ID, C.WORKFLOW_RECORD_ID, C.TRACK_ID, WR.WORKFLOW_CODE, WR.WORKFLOW_VERSION, WS.ID, WS.STEP_NAME, FDE.WORKFLOW_PROGRESS_ID, WP.STATUS, C.RECORD_STATUS, C.UPDATE_COUNT, FDE.CREATOR_ID, FDE.UPDATER_ID, C.UPDATE_DATE, FDE.SEQ ") ;                 
		  }
          if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_MYSQL) {
            sqlStatTmp1.append(" GROUP BY FDE.SEQ ");
          }
        }
               
        if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_ORACLE) {
          if (!Utility.isEmpty(fromDate)) {
            sqlStatTmp2.append(" AND FDE.CREATE_DATE >= to_date('" + fromDate + "', 'YYYY-MM-DD HH24:MI:SS') ");
          }
          if (!Utility.isEmpty(toDate)) {
            sqlStatTmp2.append(" AND FDE.CREATE_DATE <= to_date('" + toDate + "', 'YYYY-MM-DD HH24:MI:SS') ");
          }
		  sqlStatTmp2.append(" GROUP BY C.FORM_RECORD_ID, C.ID, C.WORKFLOW_RECORD_ID, C.TRACK_ID, WR.WORKFLOW_CODE, WR.WORKFLOW_VERSION, WS.ID, WS.STEP_NAME, WP.ID, WP.STATUS, C.RECORD_STATUS, C.UPDATE_COUNT, MWPUR.CREATOR_ID, MWPUR.UPDATER_ID, C.UPDATE_DATE, FDE.SEQ ") ;                 
        } else { 
		  if (!Utility.isEmpty(fromDate)) {
			sqlStatTmp2.append(" AND FDE.CREATE_DATE >= '" + fromDate + "' ");
		  }
		  if (!Utility.isEmpty(toDate)) {
			sqlStatTmp2.append(" AND FDE.CREATE_DATE <= '" +  toDate + "' ");
		  }          
          if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_MSSQL) {
			sqlStatTmp2.append(" GROUP BY C.FORM_RECORD_ID, C.ID, C.WORKFLOW_RECORD_ID, C.TRACK_ID, WR.WORKFLOW_CODE, WR.WORKFLOW_VERSION, WS.ID, WS.STEP_NAME, WP.ID, WP.STATUS, C.RECORD_STATUS, C.UPDATE_COUNT, MWPUR.CREATOR_ID, MWPUR.UPDATER_ID, C.UPDATE_DATE, FDE.SEQ ") ;         
          }        
          if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_MYSQL) {
            sqlStatTmp2.append(" GROUP BY FDE.SEQ ");
          }
        }
        
        sqlStat.append(sqlStatTmp1);
        sqlStat.append("UNION ");
        sqlStat.append(sqlStatTmp2);
        sqlStat = this.getFormattedSQL(sqlStat.toString());

        // Form the ORDER clause for sorting.
        if (searchForm.isSortable()) {
          String sortAttribute = searchForm.getSortAttribute();
          if (sortAttribute.indexOf(".") < 0) {
            if ("TITLE".equals(sortAttribute)){
              sortAttribute = "CREATE_DATE";
              searchForm.setSortAttribute("CREATE_DATE");
              searchForm.setSortOrder("DESC");
            }
          }
          sqlStat.append("ORDER BY " + sortAttribute + " " + searchForm.getSortOrder());
        }
  
        // Get total number of record return.
        sqlStatCnt = new StringBuffer("SELECT COUNT(DISTINCT FDE.SEQ) FROM ");
        int idx = sqlStatTmp1.indexOf("FROM ");
        sqlStatCnt.append(sqlStatTmp1.substring(idx + 5));
        if (sqlStatCnt.indexOf("GROUP BY") >= 0) {
          sqlStatCnt = new StringBuffer(sqlStatCnt.substring(0, sqlStatCnt.indexOf("GROUP BY") - 1));
        }           
        preStatCnt = dbConn.prepareStatement(sqlStatCnt.toString());
        this.setPrepareStatement(preStatCnt, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStatCnt, 2, formRecordID);        
        rsCnt = preStatCnt.executeQuery();
        while (rsCnt.next()) {
          totalNumOfRecord += rsCnt.getInt(1);
        }
        
        sqlStatCnt = new StringBuffer("SELECT COUNT(DISTINCT MWPUR.ID) FROM ");
        idx = sqlStatTmp2.indexOf("FROM ");
        sqlStatCnt.append(sqlStatTmp2.substring(idx + 5));
        if (sqlStatCnt.indexOf("GROUP BY") >= 0) {
          sqlStatCnt = new StringBuffer(sqlStatCnt.substring(0, sqlStatCnt.indexOf("GROUP BY") - 1));
        }        
        preStatCnt = dbConn.prepareStatement(sqlStatCnt.toString());
        this.setPrepareStatement(preStatCnt, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStatCnt, 2, formRecordID);
        this.setPrepareStatement(preStatCnt, 3, FormSubmission.FORM_SUBMISSION_STATU_PENDING);
        this.setPrepareStatement(preStatCnt, 4, FormSubmission.FORM_SUBMISSION_STATU_SAVED);
        this.setPrepareStatement(preStatCnt, 5, listFormSubmissionForm.getWorkflowStepID());
        this.setPrepareStatement(preStatCnt, 6, listFormSubmissionForm.getProgressID());
        this.setPrepareStatement(preStatCnt, 7, FormSubmission.FORM_SUBMISSION_STATU_SAVED);
        
        rsCnt = preStatCnt.executeQuery();
        while (rsCnt.next()) {
          totalNumOfRecord += rsCnt.getInt(1);
        }
        
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }

        // Retrieve the result in row basis.
        if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_MSSQL){
          sqlStat = this.getSelectListMSSQLForForm(sqlStat, startOffset, pageSize);
        }else{
          sqlStat = this.getSelectListSQL(sqlStat, startOffset, pageSize);	
        }
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 2, formRecordID);     
        this.setPrepareStatement(preStat, 3, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 4, formRecordID);
        this.setPrepareStatement(preStat, 5, FormSubmission.FORM_SUBMISSION_STATU_PENDING);
        this.setPrepareStatement(preStat, 6, FormSubmission.FORM_SUBMISSION_STATU_SAVED);
        this.setPrepareStatement(preStat, 7, listFormSubmissionForm.getWorkflowStepID());
        this.setPrepareStatement(preStat, 8, listFormSubmissionForm.getProgressID());
        this.setPrepareStatement(preStat, 9, FormSubmission.FORM_SUBMISSION_STATU_SAVED);
                
        rs = preStat.executeQuery();

        this.positionCursor(rs, startOffset, pageSize);

        while (rs.next() && rowLoopCnt<pageSize) {
          FormSubmission tmpFormSubmission = new FormSubmission();

          tmpFormSubmission.setID(getResultSetInteger(rs, "ID"));
          tmpFormSubmission.setTrackID(getResultSetInteger(rs, "TRACK_ID"));
          tmpFormSubmission.setFormRecordID(getResultSetInteger(rs, "FORM_RECORD_ID"));
          tmpFormSubmission.setWorkflowRecordID(getResultSetInteger(rs, "WORKFLOW_RECORD_ID"));
          tmpFormSubmission.setWorkflowCode(getResultSetString(rs, "WORKFLOW_CODE"));
          tmpFormSubmission.setWorkflowStepID(getResultSetInteger(rs, "STEP_ID"));
          tmpFormSubmission.setWorkflowStepName(getResultSetString(rs, "STEP_NAME"));    
          tmpFormSubmission.setProgressID(getResultSetInteger(rs, "PROGRESS_ID"));
          tmpFormSubmission.setSeq(getResultSetInteger(rs, "SEQ"));
          tmpFormSubmission.setStatus(getResultSetString(rs, "STATUS"));
          tmpFormSubmission.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormSubmission.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormSubmission.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormSubmission.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpFormSubmission.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpFormSubmission.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpFormSubmission.setCreatorName(UserInfoFactory.getUserFullName(tmpFormSubmission.getCreatorID()));
          tmpFormSubmission.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormSubmission.getUpdaterID()));
          tmpFormSubmission.setRecordCount(totalNumOfRecord);
                   
          tmpFormSubmission.setRowNum(startOffset++);
          ++rowLoopCnt;
          result.add(tmpFormSubmission);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }
      }
    }
  }
  
  /**
   * get all list for audit trail
   * @param searchForm
   * @return
   * @throws ApplicationException
   */
  public synchronized List getFormAuditTrailWholeList(
      AbstractSearchForm searchForm)
      throws ApplicationException {
    String formRecordID = ((ListFormSubmissionForm)searchForm).getFormRecordID();
    PreparedStatement preStat = null;
    PreparedStatement preStat2 = null;
    PreparedStatement preStatCnt = null;
    ResultSet rs = null;
    ResultSet rs2 = null;
    ResultSet rsCnt = null;
    StringBuffer sqlStat = new StringBuffer();
    StringBuffer sqlStatCnt = new StringBuffer("SELECT COUNT(DISTINCT FDE.SEQ) FROM ");
    List result = new ArrayList();
    int totalNumOfRecord = 0;
    int rowLoopCnt = 0;
    int startOffset = TextUtility.parseInteger(searchForm.getCurStartRowNo());
    int pageSize = TextUtility.parseInteger(searchForm.getPageOffset());
    
    ListFormSubmissionForm listFormSubmissionForm = (ListFormSubmissionForm)searchForm;
    WorkflowStepDAObject workflowStepDAO = new WorkflowStepDAObject(this.sessionContainer,this.dbConn);
    String fromDate = listFormSubmissionForm.getFromDate();
    String toDate = TextUtility.dbDateAdder(listFormSubmissionForm.getToDate(), 1);
    String basicSearchKeyword = listFormSubmissionForm.getBasicSearchKeyword();
    String searchSubmitter = listFormSubmissionForm.getSearchSubmitter();
    StringBuffer sqlStat2 = new StringBuffer();
    String workflowRecordID = listFormSubmissionForm.getWorkflowRecordID();
    String tmpStepIDStr = "";
 
    synchronized(dbConn) {
      try {
               
        //THE RECORD FROM FORM MONITOR
        sqlStat.append("SELECT DISTINCT C.ID, C.TRACK_ID, C.FORM_RECORD_ID, C.WORKFLOW_RECORD_ID, WR.WORKFLOW_CODE, C.IP,C.GUEST_NAME,C.EMAIL,C.CONTACT_INFO, C.DMS_PARENT_ID, C.STATUS,C.RECORD_STATUS,C.UPDATE_COUNT, FDE.CREATOR_ID, MAX(FDE.CREATE_DATE) CREATE_DATE, FDE.SEQ ");
        sqlStat.append("FROM FORM_SUBMISSION C ");
        sqlStat.append("LEFT JOIN WORKFLOW_RECORD WR ON WR.ID = C.WORKFLOW_RECORD_ID ");
        sqlStat.append("LEFT JOIN FORM_DATA_ELEMENT FDE ON FDE.SUBMISSION_ID = C.ID  ");
        sqlStat.append("WHERE (FDE.SUBMIT_FLAG <> ? ) "); 
        sqlStat.append("AND C.RECORD_STATUS = ? AND C.FORM_RECORD_ID = ? ");
        sqlStat.append("AND C.ID = " + listFormSubmissionForm.getSubmissionID()+ " ");
                
        sqlStat.append("AND C.STATUS <> '" + FormSubmission.FORM_SUBMISSION_STATU_SAVED + "' ");
        if (!Utility.isEmpty(searchSubmitter) && !"null".equals(searchSubmitter)){
          sqlStat.append("AND C.CREATOR_ID = " + searchSubmitter + " ");
        }
          
        if(!Utility.isEmpty(basicSearchKeyword)){
          // For Text Box
          sqlStat2.append("SELECT DISTINCT E.SUBMISSION_ID FROM FORM_DATA_ELEMENT E ");
          sqlStat2.append("INNER JOIN FORM_DATA D ON D.DATA_ELEMENT_ID = E.ID ");
          sqlStat2.append("LEFT JOIN WORKFLOW_PROGRESS WP ON E.WORKFLOW_PROGRESS_ID = WP.ID ");
          String searchField = searchForm.getBasicSearchField();
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          sqlStat2.append("WHERE D.DATA_STRING " + searchForm.getBasicSearchType() + " ? ");
          if(searchForm.isSearchable()){
            sqlStat2.append("AND E.ELEMENT_ID = ? ");
          }
         
          preStat2 = dbConn.prepareStatement(sqlStat2.toString());
          this.setPrepareStatement(preStat2, 1, searchKeyword);  
          if(searchForm.isSearchable()){  
            this.setPrepareStatement(preStat2, 2, searchField);
          }
            
          rs2= preStat2.executeQuery();
          String submissionID = "";
          while (rs2.next()) {
            submissionID += ((submissionID.length()>0)?",":"") + getResultSetInteger(rs2, "SUBMISSION_ID");
          }
          // For Select Box, Radio Button, Check Box
          sqlStat2 = new StringBuffer();
          sqlStat2.append("SELECT DISTINCT E.SUBMISSION_ID ");
          sqlStat2.append("FROM FORM_DATA_ELEMENT E INNER JOIN FORM_DATA D ON D.DATA_ELEMENT_ID = E.ID ");
          sqlStat2.append("INNER JOIN FORM_SELECTION_FIELD F ON E.ELEMENT_ID = F.ELEMENT_ID ");
          sqlStat2.append("INNER JOIN FORM_SELECTION_FIELD_OPTION G ON G.SELECTION_FIELD_ID = F.ID ");
          sqlStat2.append("LEFT JOIN WORKFLOW_PROGRESS WP ON E.WORKFLOW_PROGRESS_ID = WP.ID ");
          sqlStat2.append("WHERE D.DATA_STRING = G.START_VALUE ");
          sqlStat2.append("AND G.LABEL " + searchForm.getBasicSearchType() + " ? ");
          if(searchForm.isSearchable()){
            sqlStat2.append("AND E.ELEMENT_ID = ? ");
          }
          
          preStat2 = dbConn.prepareStatement(sqlStat2.toString());
          this.setPrepareStatement(preStat2, 1, searchKeyword);  
          if(searchForm.isSearchable()){  
            this.setPrepareStatement(preStat2, 2, searchField);
          }
          rs2= preStat2.executeQuery();
          while (rs2.next()) {
            submissionID += ((submissionID.length()>0)?",":"") + getResultSetInteger(rs2, "SUBMISSION_ID");
          }

          if (!Utility.isEmpty(submissionID)) {
            sqlStat.append("           AND C.ID IN ("+submissionID+") ");
            sqlStat.append("           AND C.ID IN ("+submissionID+") ");
          }else{
            throw new ApplicationException(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR);
          }
          //}
          try { rs2.close(); } catch (Exception ignore) {} finally { rs2 = null; }
          try { preStat2.close(); } catch (Exception ignore) {} finally { preStat2 = null; }
        }
        
//        sqlStat.append(attachedString);
        if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_ORACLE) {
         if (!Utility.isEmpty(fromDate)) {
            sqlStat.append(" AND FDE.CREATE_DATE >= to_date('" + fromDate + "', 'YYYY-MM-DD HH24:MI:SS') ");
          }
          if (!Utility.isEmpty(toDate)) {
            sqlStat.append(" AND FDE.CREATE_DATE <= to_date('" +toDate + "', 'YYYY-MM-DD HH24:MI:SS') ");
          }
		  sqlStat.append("GROUP BY C.ID, C.TRACK_ID, C.FORM_RECORD_ID, C.WORKFLOW_RECORD_ID, WR.WORKFLOW_CODE, C.IP,C.GUEST_NAME,C.EMAIL,C.CONTACT_INFO, C.DMS_PARENT_ID, C.STATUS,C.RECORD_STATUS,C.UPDATE_COUNT, FDE.CREATOR_ID, FDE.SEQ ") ;        
          
        } else { 
          if (!Utility.isEmpty(fromDate)) {
			sqlStat.append(" AND FDE.CREATE_DATE >= '" + fromDate + "' ");
		  }
		  if (!Utility.isEmpty(toDate)) {
			sqlStat.append(" AND FDE.CREATE_DATE <= '" +  toDate + "' ");
		  }   
          if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_MSSQL) {			      
			sqlStat.append("GROUP BY C.ID, C.TRACK_ID, C.FORM_RECORD_ID, C.WORKFLOW_RECORD_ID, WR.WORKFLOW_CODE, C.IP,C.GUEST_NAME,C.EMAIL,C.CONTACT_INFO, C.DMS_PARENT_ID, C.STATUS,C.RECORD_STATUS,C.UPDATE_COUNT, FDE.CREATOR_ID, FDE.SEQ ") ;                 
          }          
          if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_MYSQL) {
            sqlStat.append("GROUP BY FDE.SEQ ");
          }
        }
        
        sqlStat = this.getFormattedSQL(sqlStat.toString());

        // Form the ORDER clause for sorting.
        if (searchForm.isSortable()) {
          String sortAttribute = searchForm.getSortAttribute();
          if (sortAttribute.indexOf(".") < 0) {
            if ("TITLE".equals(sortAttribute)){
              sortAttribute = "CREATE_DATE";
              searchForm.setSortAttribute("CREATE_DATE");
              searchForm.setSortOrder("DESC");
            }
            if ("WORKFLOW_CODE".equals(sortAttribute)){
              sortAttribute = "WR." + sortAttribute;
            }else if ("CREATOR_ID".equals(sortAttribute)){
              sortAttribute = "FDE." + sortAttribute;
            }else{
              sortAttribute = "C." + sortAttribute;
            }
          }
          sqlStat.append("ORDER BY " + sortAttribute + " " + searchForm.getSortOrder());
        }
  
        // Get total number of record return.
        int idx = sqlStat.indexOf("FROM ");
        sqlStatCnt.append(sqlStat.substring(idx + 5));
        if (sqlStatCnt.indexOf("GROUP BY") >= 0) {
          sqlStatCnt = new StringBuffer(sqlStatCnt.substring(0, sqlStatCnt.indexOf("GROUP BY") - 1));
        }                  
        preStatCnt = dbConn.prepareStatement(sqlStatCnt.toString());
        this.setPrepareStatement(preStatCnt, 1, FormSubmission.FORM_SUBMISSION_STATU_DRAFT);
        this.setPrepareStatement(preStatCnt, 2, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStatCnt, 3, formRecordID);
        
        rsCnt = preStatCnt.executeQuery();
        while (rsCnt.next()) {
          totalNumOfRecord += rsCnt.getInt(1);
        }
       
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }

        // Retrieve the result in row basis.
        sqlStat = this.getSelectListSQL(sqlStat, startOffset, pageSize);
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, FormSubmission.FORM_SUBMISSION_STATU_DRAFT);
        this.setPrepareStatement(preStat, 2, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 3, formRecordID);     
        
        rs = preStat.executeQuery();

        this.positionCursor(rs, startOffset, pageSize);

        while (rs.next() && rowLoopCnt<pageSize) {
          FormSubmission tmpFormSubmission = new FormSubmission();

          tmpFormSubmission.setID(getResultSetInteger(rs, "ID"));
          tmpFormSubmission.setTrackID(getResultSetInteger(rs, "TRACK_ID"));
          tmpFormSubmission.setFormRecordID(getResultSetInteger(rs, "FORM_RECORD_ID"));
          tmpFormSubmission.setWorkflowRecordID(getResultSetInteger(rs, "WORKFLOW_RECORD_ID"));
          tmpFormSubmission.setWorkflowCode(getResultSetString(rs, "WORKFLOW_CODE"));         
          tmpFormSubmission.setSeq(getResultSetInteger(rs, "SEQ"));
          tmpFormSubmission.setStatus(getResultSetString(rs, "STATUS"));
          tmpFormSubmission.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpFormSubmission.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpFormSubmission.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpFormSubmission.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));          
          tmpFormSubmission.setCreatorName(UserInfoFactory.getUserFullName(tmpFormSubmission.getCreatorID()));
          tmpFormSubmission.setUpdaterName(UserInfoFactory.getUserFullName(tmpFormSubmission.getUpdaterID()));
          tmpFormSubmission.setRecordCount(totalNumOfRecord);

          tmpFormSubmission.setRowNum(startOffset++);
          ++rowLoopCnt;
          result.add(tmpFormSubmission);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }
      }
    }
  }

  public String getSubMissionIDFromTrackID(String trackID, String formRecordID, String workflowRecordID) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat=new StringBuffer();
    ResultSet rs = null;
    String result=new String();
    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.TRACK_ID, A.FORM_RECORD_ID, A.WORKFLOW_RECORD_ID, A.IP, A.GUEST_NAME, A.EMAIL, A.CONTACT_INFO, A.DMS_PARENT_ID, A.STATUS, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   FORM_SUBMISSION A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? AND A.TRACK_ID = ? ");
        sqlStat.append("  AND  A.FORM_RECORD_ID = ? AND A.WORKFLOW_RECORD_ID = ? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 2, trackID);
        this.setPrepareStatement(preStat, 3, formRecordID);
        this.setPrepareStatement(preStat, 4, workflowRecordID);
        
        rs = preStat.executeQuery();
        while (rs.next()) {
        result=getResultSetString(rs, "ID");  
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }
  
  protected StringBuffer getSelectListMSSQLForForm(StringBuffer sbSQL, int startOffset, int pageSize) {
    StringBuffer sbResult = new StringBuffer(sbSQL.toString());
    // SELECT TOP 60 FROM (SELECT * FROM tablea) DCI_TABLE ORDER BY DCI_TABLE.COLUMN
	StringBuffer resultStr = new StringBuffer("SELECT TOP " + (startOffset + pageSize - 1) + " * FROM ( ");
    if (sbResult.toString().toUpperCase().indexOf("ORDER") > 0){
      String s2 = sbResult.toString().substring(0, sbResult.toString().toUpperCase().indexOf("ORDER"));
      resultStr.append(s2);
      String s1 = sbResult.toString().substring(sbResult.toString().toUpperCase().indexOf("ORDER") + 9);          	  
      String tableName = "DCI_TABLE.";    	  
      if (s1.indexOf(".")>-1){
    	tableName = s1.substring(0, s1.indexOf("."));
      }
      String orderByStr = TextUtility.replaceString(s1, tableName + ".", "DCI_TABLE.");                  	  
      resultStr.append( " ) DCI_TABLE ORDER BY ");
      resultStr.append(orderByStr);     	  
    } else {
      resultStr.append(sbResult.toString());
      resultStr.append(") DCI_TABLE ");
    }
    sbResult = resultStr;
    return(sbResult);
  }

  /**
   * check whether display the separate IconHistory.gif link in 
   * the FormSubmission page when the FormRecord is bind with workflowRecord.
   * @param formRecordID formRecordID.
   * @return true display.false not display.
   * @throws ApplicationException ApplicationException.
   */
  public synchronized boolean isDisplayFormSubmissionHistory(
        Integer formRecordID) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    boolean isDisplayHistoryLink = false;
    
    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID ");
        sqlStat.append("FROM   FORM_SUBMISSION A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? AND A. FORM_RECORD_ID = ? ");
        sqlStat.append("AND A.CREATOR_ID = ? AND A.TRACK_ID IS NULL ");
        sqlStat.append("AND A.WORKFLOW_RECORD_ID IS NULL");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 2, formRecordID);
        this.setPrepareStatement(preStat, 3, sessionContainer.getUserRecordID());
        
        rs = preStat.executeQuery();
        if (rs.next())
        {
          isDisplayHistoryLink = true;
        }
        return (isDisplayHistoryLink);
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }
}
